I have been messing with range-based for loops, like this one:
int a[] = {1, 2, 3, 4};
for(auto i : a){
cout << i;
}
(Correct me here if I'm wrong)I suppose that i
assigned at start of every iteration with the next value in sequence container a
like:
i = a[0]
… iteration 1
i = a[1]
… iteration 2
…
i = a[9]
… iteration 10
I wanted to ask how does this works when loop control variable is a reference:
for(int &i : a){...}
Since a reference is not assigned at initialization but binded, and the binding never changes then how does i
iterates through a
saving value of an element of a
in a given iteration but when a reference is assigned except in the declaration it is like assigning the original variable. To change array elements we have to use reference, my question is how a single reference can be binded to different variables(i.e. elements of a
during looping) as every element can be modified with the same reference variable inside the loop.
Thanks