I have created a C++ program in order to test the functionality of passing parameters by reference for functions.
#include <iostream>
using namespace std;
int f(int &b) {
b = b + 1;
cout << b << endl;
return b;
}
int main() {
int t = 10;
cout << f(t) << " " << t << endl;
//cout << f(&t) << " " << t << endl;
system("PAUSE");
return 0;
}
Could you please explain to me why does this program won’t affect the value of t after the execution of the f function? The b parameter in passed be reference, so I thought that it’s value would change after the execution of the program because I am working with the actual variable from the main function, not a copy of it. In this case, I would expect it to be 11, but it’s not affected by the execution of the program.
Why is this happening?
The value of
tdoes get incremented. You’ll see this if you split the output statement in two:With your original single output statement:
the compiler is free to evaluate
tbeforef(t), producing in the output you’re seeing. For more info, see cout << order of call to functions it prints?