Search code examples
c++referenceauto

Within the context of the code below, why is "cout << c" legal while "c = "x"" illegal?


I'm new to C++ and is trying to learn the concept of keyword 'auto' and reference. I saw this question and answer online.

Is the following range for legal? If so, what is the type of c?

const string s = "Keep out!";
for (auto &c : s){ /*... */ }

And the answer is:

Depending on the code within for loop body. For example:

cout << c;  // legal.
c = 'X';    // illegal.

No explanation was provided. Could someone explain why this is the case?


Solution

  • Because the string is constant, you may not modify it. The range-based loop is using the type auto & which will effectively become const char &. That means you're referencing characters in the actual string, not copies of them.