reference can't be bind to different object

As far as I know, reference can't be bind to different object
But, why the reference c in code below can be bind to different object?

string s("Hello world");
for(auto &c : s)
c = toupper(c);
'c' is 'created' at every iteration, more or less as in the following second loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <limits>
#include <string>

void waitForEnter();

int main()
{
    std::string s("Hello world");
    for(auto& c : s) { c = std::toupper(c); }
    std::cout << "Now 's' is \"" << s << "\".\n";
    for(size_t i{}; i<s.length(); ++i) {
        char& c = s.at(i);
        c = std::tolower(c);
    }
    std::cout << "And now is \"" << s << "\".\n";
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Last edited on
Hm, it is reasonable, great thanks.
You don’t need to blindly trust me, of course :-)
If you read here
http://en.cppreference.com/w/cpp/language/range-for
the statement
for ( range_declaration : range_expression ) loop_statement
is turned into
1
2
3
4
5
6
7
8
9
10
11
12
13
{

    auto && __range = range_expression ;
    for (auto __begin = begin_expr, __end = end_expr;

            __begin != __end; ++__begin) {

        range_declaration = *__begin;
        loop_statement

    }

} 


As you can see, range_declaration is defined inside the body of the loop, i.e. at every iteration.
Perhaps I should have quoted it from the very beginning, I’m sorry.
Topic archived. No new replies allowed.