Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 range-based for() loops evaluate once or multiple times? [duplicate]

Given this C++11 example code:

for ( const auto &foo : bar() ) {     // ... do something with foo... } 

Is it guaranteed by the standard that the expression bar() in this example is evaluated only once?

Or could it end up being called at every iteration of the loop?

like image 332
Stéphane Avatar asked Apr 28 '13 04:04

Stéphane


People also ask

Are there range-based for loops in C?

Range-based for loop (since C++11) 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.

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once.

What is range loop?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Is foreach slower than for C++?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.


1 Answers

It is evaluated only once. The standard says that the range-based for loop is equivalent to this:

§6.5.4 The range-based for statement [stmt.ranged]

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

with range-init being equivalent to ( bar() ) in your case (the expression you specify, surrounded by parenthesis). That expression is only evaluated once as you can see.

like image 80
Mat Avatar answered Oct 05 '22 07:10

Mat