C ++ reference in a for loop

As with the for loop of the following code, why should we use reference ( &c

) to change values c

. Why can't we use c

in a loop for

. Maybe it's about the difference between an argument and a parameter?

#include "stdafx.h"
#include<iostream>
#include<string>

using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
    string s1("Hello");
        for (auto &c : s1)
            c = toupper(c);
            cout << s1 << endl;
    return 0;
}

      

+3


source to share


3 answers


If you don't use a link, then the code will logically look like

for ( size_t i = 0; i < s1.size(); i++ )
{
    char c = s1[i];
    c = toupper( c );
}

      

that is, each time in the loop, the object c

that receives the copy will be modified s1[i]

. s1[i]

itself will not be changed. However, if you write

for ( size_t i = 0; i < s1.size(); i++ )
{
    char &c = s1[i];
    c = toupper( c );
}

      



then in this case c

is a reference to s1[i]

when operator

    c = toupper( c );

      

changes s1[i]

himself.

The same is true for an expression-based range.

+3


source


When:



for (auto cCpy: s1)

cCpy is a copy of the character at the current position.

When:



for (auto & cRef: s1)

cRef is a reference for the current position character.

It has nothing to do with arguments and parameters. They are related to function calls (you can read about this here: Parameter vs Argument ).

+4


source


You can't just use c

, because this will copy, create a copy of each character, update the copy, and then throw it away. References (or pointers) are constructs used by C ++ to propagate changes to objects.

+1


source







All Articles