Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference 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 range for loop to iterate over every character in a string and change it to uppercase, which is pretty straightforward. What puzzles me is that the reference c seems to change at runtime. Elsewhere in the book, the authors mention that references, not being objects, cannot change in runtime. Can anyone shed some light into how exactly is this code interpreted by the compiler?

like image 521
Chele Avatar asked Mar 19 '23 11:03

Chele


1 Answers

You're right that a reference can't be changed to refer to a different object; it must be initialised to refer to a particular object, and remains an alias for that object for its whole lifetime.

In this case, the reference doesn't change; instead, a new reference is created and destroyed for each iteration of the loop. This range-style loop is defined to be (more-or-less) equivalent to the old-style loop

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

Written like this, it's clear that there's a new reference each time, not a single reference that's (somehow) updated.

like image 113
Mike Seymour Avatar answered Mar 29 '23 20:03

Mike Seymour