Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ for loop temporary variable use

Tags:

c++

for-loop

Which of the following is better and why? (Particular to c++)

a.

int i(0), iMax(vec.length());//vec is a container, say std::vector
for(;i < iMax; ++i)
{
  //loop body
}

b.

for( int i(0);i < vec.length(); ++i)
{
  //loop body
}

I have seen advice for (a) because of the call to length function. This is bothering me. Doesn't any modern compiler do the optimization of (b) to be similar to (a)?

like image 493
Amol Gawai Avatar asked Jun 25 '09 05:06

Amol Gawai


2 Answers

Example (b) has a different meaning to example (a), and the compiler must interpret it as you write it.

If, (for some made-up reason that I can't think of), I wrote code to do this:

for( int i(0);i < vec.length(); ++i)
{
    if(i%4 == 0)
       vec.push_back(Widget());
}

I really would not have wanted the compiler to optimise out each call to vec.length(), because I would get different results.

like image 72
Andrew Shepherd Avatar answered Oct 01 '22 14:10

Andrew Shepherd


I like:

for (int i = 0, e = vec.length(); i != e; ++i)

Of course, this would also work for iterators:

for (vector<int>::const_iterator i = v.begin(), e = v.end(); i != e; ++i)

I like this because it's both efficient (calling end() just once), and also relatively succinct (only having to type vector<int>::const_iterator once).

like image 24
Assaf Lavie Avatar answered Oct 01 '22 16:10

Assaf Lavie