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

  • A+
Category:Languages
#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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: