Alex Rivera | Logout

In a "i < vector.size()" loop condition, is size() called each iteration?

Asked 2010-10-10T18:37:13.687
48

In the following code:

std::vector<int> var;
for (int i = 0; i < var.size(); i++);

Is the size() member function called for each loop iteration, or only once?

Edit
Report

2 Answers

2

As other have said

  • the semantics must be as if it were called each time
  • it is probably inlined, and is probably a simple function

on top of which

  • a smart enough optimizer may be able to deduce that it is a loop invariant with no side effects and elide it entirely (this is easier if the code is inlined, but may be possible even if it is not if the compiler does global optimization)
answered 2010-10-10T18:44:49.193
2

But it could be done in this way (providing that this loop intends to only read/write without actually changing the size of a vector):

for(vector<int>::size_type i=0, size = var.size(); i < size; ++i) 
{
//do something
}

In the loop above you have just one call to size independently from size being inlined or not.

answered 2010-10-10T18:53:42.517

Your Answer