Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C++11 range-based for loop condition get evaluated every cycle?

for(auto& entity : memoryManager.getItems()) entity->update(mFrameTime); 

If memoryManager contains 1000 items, does memoryManager.getItems() get called 1000 times or only one at the beginning of the loop?

Does the compiler run any optimization with -O2 (or -O3)?

(memoryManager.getItems() returns a std::vector<Entity*>&)

like image 812
Vittorio Romeo Avatar asked Apr 02 '13 13:04

Vittorio Romeo


People also ask

Does for loop check condition every time?

Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.

How does range-based for loop work?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Does a for loop check condition first?

while Loops ( Condition-Controlled Loops )While loops check for the stopping condition first, and may not execute the body of the loop at all if the condition is initially false.


1 Answers

It is only evaluated once. The standard defines a range-based for statement as equivalent to:

{     auto && __range = range-init;     for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) {         for-range-declaration = *__begin;         statement     } } 

where range-init is the expression (surrounded by parentheses) or braced-init-list after the :

like image 199
Mike Seymour Avatar answered Oct 04 '22 15:10

Mike Seymour