Stéphane Stéphane - 6 months ago 30
C++ Question

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

Given this C++11 example code:

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

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

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

Mat Mat

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;

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.