#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("BAC.TXT");
void eval(int a, int b, int &rez)
{
rez = a + b;
}
int main()
{
int nr;
int s;
fin >> s;
while (fin >> nr)
eval(s, nr, s);
cout << s << '\n';
return 0;
}
So I have this code snippet. I am reading numbers from a file and keeping track of their sum using a given function called “eval”. I know it could be considered bad code to pass a parameter twice (in such a given instance) rather than using another variable (not sure, though, if it is bad code or not, in my case). My problem is: will it change the value of variable s
? Again, I am passing it once by value and once by reference! I have written the code on my PC and it does change the value of s
. Now my question would be: why? If I am asking this in a right way: what happens “in the background”?
The fact that a
is a copy of s
is actually a red herring. Maybe that caused your confusion, but its just a copy. Consider that you could call the function like this
auto temp = s;
eval(temp,nr,s);
to get the exact same result. Inside the function rez
is a reference to s
, hence modifications on it will be reflected on s
in main
. In other words, rez
is an alias for s
, while a
has no relation whatsoever to s
, they just happen to hold the same value.
This question is related to the behavior of functions parameters and reference/pointers.
When you pass a value to a function, it copies the value you give to a local variable inside the function.
in your case, when you pass 's', it copies it to 'a' like if you would do it in your main: int a = s (this is what is going on)
The same applies to the reference. when you pass 's' to the third parameter, it does this:
int &rez = s
When you pass it by reference, it is sort of taking the address of the variable instead of the value itself and copying this address to a local variable that is already dereferenced. (pointer stuff)
So the value is changed.
See the video related to pointers and then reference on 'the Cherno Project' youtube channel for better comprehension of the subject:
Pointers
References
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