Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a parameter if it is passed twice? Once by value and once by reference? Will it be modified or not?

#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”?

like image 254
M.Ionut Avatar asked Dec 13 '22 13:12

M.Ionut


2 Answers

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.

like image 77
463035818_is_not_a_number Avatar answered Dec 25 '22 23:12

463035818_is_not_a_number


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

like image 44
Narice Avatar answered Dec 25 '22 22:12

Narice