Search code examples
c++loopsrangeauto

In 'for (auto c : str)' what exactly is c?


If I declare:

string s = "ARZ";

And then run the following code:

for (auto& c : s) {
  cout << (void*)&c << endl;
}

the results will correspond to the addresses of s[0], s[1] and s[2] respectively.

If I remove the & and run:

for (auto c : s) {
  cout << (void*)&c << endl;
}

the address of c is always the same.

Presumably c is just a pointer into the vector and it's value advances by sizeof(char) with each loop but I'm finding it hard to get my head round why I'm not required to write *c to access the string char values.

And finally if I run:

for (auto c: s) {
  c='?';
  cout << c << endl;
}

It prints out 3 question marks.

I'm finding it hard to fathom what c actually is?


Solution

  • In 'for (auto c : str)' what exactly is c?

    It's a local variable whose scope is the entire for block and has char type.

    for (auto c : str) { loop_statement }
    

    is equivalent to

    {
        for (auto __begin = str.begin(), __end = str.end(); __begin != __end; ++__begin) {
            auto c = *__begin;
            loop_statement
        }
    }
    

    On some implementations, under some conditions, since the lifetime of c ends before the lifetime of next-iteration's c begins, it gets allocated at the same place and gets the same address. You cannot rely on that.