On Friday 05 March 2010 07:44:22 am rgheck wrote:
> On 03/05/2010 07:16 AM, Edwin Leuven wrote:
> > Abdelrazak Younes wrote:
> >> On 03/05/2010 11:56 AM, Edwin Leuven wrote:
> >>> now when looping i write something like this:
> >>>
> >>> row_type const nrows = row_info.size();
> >>> for (row_type r = 0; r < nrows; ++r) {
> >>>
> >>> are compilers these days smart enough so that we can simply write:
> >>>
> >>> for (row_type r = 0; r < row_info.size(); ++r) {
> >>
> >> I guess it depends of the constness of row_info...
> >
> > it's a non-const std::vector
> >
> > what if i declared
> >
> > row_type nrows() const {return row_info.size();}
> >
> > and then do
> >
> > for (row_type r = 0; r < nrows(); ++r)
> >
> > ?
>
> I think gcc would give you a warning, to the effect of "Qualifier on
> return value is ignored". This is because row_type is not of object type.
>
> Moreover, you could perfectly well do:
> for (row_type r = 0; r < nrows(); ++r)
> row_info.clear();
> if row_info is non-const. Then nrows() returns 0 on the second time
> through, and the loop terminates, as it should. This suggests a reason that
> for (row_type r = 0; r < row_info.size(); ++r) {
> might be a little safer than
> row_type const nrows = row_info.size();
> for (row_type r = 0; r < nrows; ++r) {
> when row_info is non-const.
>
> Richard
Actually, if row_info is going to change within the loop then r <
row_info.size() is the only correct thing to do. With this we are telling the
compiler to repeatedly evaluate row_info.size() before make the looping
decision.
A compiler that caches the value of row_info.size() during its first
evaluation is buggy. Of course, if this code is part of a const method of the
same class as row_info then an optimization would be to cache the value on
first evaluation.
Even if you declare nrows() to be a const method, it can be used within a
non-const method in the same class without errors or warnings. The const-ness
of nrows() method only means that at the time it is called, it does nothing
to change the associated class during the lifetime of its execution during
that call.
I think your question is about the optimization - does the compiler cache the
row_info.size() value? Compiler optimizations have come a long way and this
should happen in commercial compilers even if GCC doesn't recognize the
optimization opportunity. If you are not sure, then it is best to play it
safe and introduce a new const variable that you code to cache the container
size. This also helps with debugging. Most compilers are smart enough to
optimize out const "variables" - it is one of the simpler things to achieve.
GCC does propagate constants.
-- Manoj