I wonder if you could change the value of an external input variable that is treated as a parameter of a function, I remember seeing a way to do it but I don't remember very well.
Suppose we use a function for the sum of two numbers, which has two parameters, the first parameter will be introduced a variable with the value 5, and in the second a constant with the value 3.
int numero = 5;
void sumaNumero(int num1, int num2){
num1 = num1 + num2;
}
sumaNumero(numero, 3);
cout << "Resultado de la suma = " << numero << endl;
The result of the sum should be stored in the variable. Would this procedure really work?
As you put it, no .
But... making a little change...
With the original code, you were passing the argument by value , so what you got inside the function was a copy , and its possible changes were limited to inside the function.
With the modification that I indicate, you pass it by reference ; thus, any modification if visible outside the function.
You can consult What is the difference between
int *
andint &
? for more information.You have to use a reference:
It could also be done with pointers, but then the code would be a bit uglier (and for no apparent reason in this case):
Although for specific cases like the one in your example I would suggest you return the value via
return
since the result is more logical: