LiuHao
LiuHao

Reputation: 562

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;
}

Upvotes: 5

Views: 5597

Answers (3)

Maciej Oziębły
Maciej Oziębły

Reputation: 2039

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").

Upvotes: 7

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

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.

Upvotes: 3

TartanLlama
TartanLlama

Reputation: 65600

You can't just use c, because that would copy create a copy of each character, update the copy, then throw it away. References (or pointers) are the constructs C++ uses to propagate the changing of objects.

Upvotes: 1

Related Questions