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;
}
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").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With