dylanG35
dylanG35

Reputation: 13

Define a reference in a range-based for loop

I am totally new to C++, so the question may be a bit naive :D! Recently I have been confused by a question relating to declaration in the range-based for. We are allowed to write something like:

for(int &i : vec)

Then a confusion occurred. It seems to me, the variable i will be defined once and be assigned to different value in each loop. But in the case above, i is a reference which is just an alias and should be bound to only one object. I think one way to come around this is to think that a new i is defined each time. I searched for further explanation on this and found a page: range for!:


Syntax attr(optional)

for ( range_declaration : range_expression ) loop_statement 

Explanation

The above syntax produces code similar to the following (__range, __begin and __end are for exposition only):

auto && __range = range_expression ;
for (auto __begin = begin_expr,

            __end = end_expr;

        __begin != __end; ++__begin) {

    range_declaration = *__begin;
    loop_statement
}

The 'range_declaration' is defined within for loop. But isn't a variable defined inside a loop reused which means the reference i defined in the first example is reused? Still I am confused and could any one please give me some hints. Thanks!

Upvotes: 1

Views: 122

Answers (1)

A variable defined inside the loop body is local to the loop body and thus destroyed and re-defined each time the loop iterates. So the int &i is freshly initialised in each iteration and there's no problem.

It might be clearer if we perfrom the substitutions (with some simplifications) into the example you've posted:

for (auto b = begin(vec), e = end(vec); b != e; ++b) {
  int &i = *b;
  //loop statement
}

Upvotes: 4

Related Questions