Alex Rivera | Logout

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

Asked 2013-04-28T04:21:54.370
28

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?

Edit
Report

1 Answer

34

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.

answered 2013-04-28T04:28:34.697

Your Answer