Using a reference as the iterator in for loop

I am reading the 5th edition of c++ Primer. I come across the following code snippet for which I have the doubt:

int num1=2;
int num2=3;
int &ref_num = num1  //Ok, ref_num is a non-constant int type reference to num1
int &ref_num = num2 //Error, as ref_num is already declared in prev statement

So, we can not bind reference variable to multiple objects at the same time. But it also says, we can go through a string literal using a reference control variable.

string line("Hello");
for(auto &ref_var : line)

So, in this case, my reference variable "ref_var" will be bound to each element of the string object "line". How come?

Upvotes: 2

Views: 199

Answers (1)

M.M
M.M

Reputation: 141544

The range-based for loop is equivalent to this (pseudocode):

for (i = 0; i < line.size(); ++i)
{
    auto& ref_var = line[i];
    // rest of body here
}

In other words, the control variable is actually redeclared each loop iteration.

Upvotes: 5

Related Questions