1

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!

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Angew, thank you very much. I get it now. I think my misunderstanding lies in not to be clear about variables defined in a loop. I thought variables is defined once and will be reused later. To be certain, assume the for loop you wrote above has 10 iterations. In the first round, reference i is defined and after the closing curly brace is met, i is destroyed. Now in the second round, a new reference i is defined and will be discarded once the second round is finished. This pattern continues till the end. Have I got it right? Thanks!
@dylanG35 Yes, you got it right. You can easily verify this yourself by creating a class which does something observable (e.g. write to std::cout) in its constructor and destructor, and declaring a local variable of this class type inside the loop. You'll see the ctor and dtor are invoked in each iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.