Called function does not change variable in main with same name [closed]
Solution 1:
The variables x
and y
in the function su
are different variables than x
and y
in the function main
. Therefore, the line
x = x + y;
will only affect the variable x
in the function su
, but not the variable x
in the function main
.
If you want to change the variable x
in the function main
too, then you must change the line
su(x, y);
to:
x = su(x, y);
If you want the variables x
and y
in the function su
to not be different variables, so that changing them will also affect the corresponding variables of the function main
, then you should instead make the function su
take references to variables:
void su( int &x, int &y )
{
x = x + y;
}
Now, changing the value of x
and y
in the function su
will also change the variable x
and y
in the function main
.
However, the first solution is probably better.