Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference in for loop

As in the for loop of the following code, why do we have to use reference (&c) to change the values of c. Why can't we just use c in the for loop. Maybe it's about the the difference between argument and 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;
}
like image 523
LiuHao Avatar asked Dec 24 '22 19:12

LiuHao


2 Answers

In case of:

for (auto cCpy : s1)

cCpy is a copy of character on current position.

In case of:

for (auto &cRef : s1)

cRef is a reference to character on current position.

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

like image 192
Maciej Oziębły Avatar answered Jan 11 '23 22:01

Maciej Oziębły


If not to use reference then the code will look logically something like

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

that is each time within the loop there will be changed object c that gets a copy of s1[i]. s1[i] itself will not be changed. However if you will write

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

then in this case as c is a reference to s1[i] when statement

    c = toupper( c );

changes s1[i] itself.

The same is valid for the range based for statement.

like image 45
Vlad from Moscow Avatar answered Jan 11 '23 22:01

Vlad from Moscow