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?
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.
Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With