If you have a function like this
int add1( int n )
^^^^^
{
n++;
return n;
}
and call it like
m += add1(i);
Then the function deals with a copy of the value of vatiable i
.
You can imagine it the following way if to build it in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
int n = i;
n++;
m += n;
}
When a function is declared like this
int add1( int &n )
^^^^^
{
n++;
return n;
}
Then it means that the parameter is a reference to the corresponding original argument. You can consider it just as an alias for the argument.
In this case you can imagine it the following way if to build it in in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
i++;
m += i;
}
So the variable i
is changed twice in the function add1 because it is directly used in the function by means of the reference n
and in the control statement of the loop.