It may be called once, may be called size+1
times, or it may never be called at all. Assuming that the vector size doesn't change, your program will behave as if it had been called size+1
times.
There are two optimizations at play here: first, std::vector::size()
is probably inlined, so it may never be "called" at all in the traditional sense. Second, the compiler may determine that it evaluate size()
only once, or perhaps never:
For example, this code might never evaluate std::vector::size()
:
for(int i = 0; i < myVector.size(); ++i) { ; }
Either of these loops might evaluate std::vector::size()
only once:
for(int i = 0; i < myVector.size(); ++i) { std::cout << "Hello, world.\n"; }
for(int i = 0; i < myVector.size(); ++i) { sum += myVector[i]; }
While this loop might evaluate std::vector::size()
many times:
for(int i = 0; i < myVector.size(); ++i) { ExternalFunction(&myVector); }
In the final analysis, the key questions are:
- Why do you care?, and
- How would you know?
Why do you care how many times size()
is invoked? Are you trying to make your program go faster?
How would you even know? Since size()
has no visible side-effects, how would you even know who many times it was called (or otherwise evaluated)?