Link apparently changing at runtime in C ++ 11

Consider the following simple code in C ++ 11, taken from C ++ Primer, 5th Edition :

#include <iostream>
#include <string>

using std::cout;
using std::string;
using std::endl;

int main()
{
string s("Hello World!!!");
for (auto &c : s) // for every char in s (note: c is a reference)
c = toupper(c); // c is a reference, so the assignment changes the char
cout << s << endl;
return 0;
}

The code uses a loop range forto repeat each character in stringand change it to uppercase, which is pretty simple. What baffles me is that the link cseems to change at runtime. Elsewhere in the book, authors note that non-object links cannot change at run time. Can anyone shed some light on how exactly this code is interpreted by the compiler?

+4
source share
3 answers

, , ; .

; . ( ),

for (auto it = s.begin(); it != s.end(); ++it) {
    auto &c = *it;
    // loop body
}

: , , , (-) .

+6

for (auto &c : s) c, c .

:

for(int i = 0; i < s.length(); i++)
{
    auto &c = *(s+i);
    /*
        Do Stuff;
    */
}
+1

, , . , , .. ( )

for (auto &c : s){ // for every char in s (note: c is a reference)
    c = toupper(c);
}

the link refers to the same unique variable. With each iteration of the loop, you get a new link to the next element in s.

What you cannot do with the link really changes what it refers to, for example:

int i = 10;
int j = 20;
int& h = i;// j now refers to i
h = j; // modifies i, doesn't change what it refers to from i to j
0
source

All Articles