12

In one of the C++ books i am reading :

int v[] = {0,1,2,3,4,5,6,7,8,9};
for (auto& x : v)

When next line in the book says :

".. a reference cannot be made to refer to a different object after its initialization..."

x refers to all v's object, how does it work?

YSC
  • 36,217
  • 8
  • 89
  • 142
schanti schul
  • 603
  • 3
  • 12

2 Answers2

19

Given a range-based for loop

for ( range_declaration : range_expression ) loop_statement

It is equivalent to

{
    auto && __range = range_expression ; 
    auto __begin = begin_expr ;
    auto __end = end_expr ;
    for ( ; __begin != __end; ++__begin) { 
        range_declaration = *__begin; 
        loop_statement 
    } 
}

Here range_declaration is your auto& x, it is initialized to refer to each element at each iteration, not rebinding the same reference.

Passer By
  • 18,098
  • 6
  • 45
  • 90
14

x refers to all v's object

Not at the same time. Each time through the loop x is a new local variable that refers to a single array element.

In pseudo code¹, it's like

for (int* it = std::begin(v); it != std::end(v); ++it)
{
    int& x = *it; // new local variable
    // ...
}

¹ For specifics, refer here http://en.cppreference.com/w/cpp/language/range-for

sehe
  • 350,152
  • 45
  • 431
  • 590