#include <iostream>
usingnamespace std;
int g = 5;
int f(int& x, int& y, int z) {
if (x > y){
y = y + 2;
x = g - y;
g = z + 1;
return z - 1;
}
else{
g =g + x;
y = x - z;
x = z + 1;
return g - y;
}
}
int main () {
int x, y, z;
cin >> x >> y >> z;
cout << f (y, g, x) <<" "<< x <<" "<< y <<" "<<z<<" "<<g<<endl;
cout << f (g, z, y) <<" "<< x <<" "<< y <<" "<< z<<" "<<g<<endl;
cout << f (z, x, g) <<" "<< x <<" "<< y <<" "<< z<<" "<<g<<endl;
return 0;
}
Both programs are basically a test of how well you understand variable scope and pass-by-reference vs. pass by value. The things that look like "errors" are intentional. Remember that a parameter which is passed by value won't be changed if assigned to, and won't actually affect anything unless it is used in the calculation of the return value. However, a parameter passed by reference will be changed if it is assigned to.
This is an extremely simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void func(int &byRef, int byVal)
{
byRef += byVal;
byVal += byRef;
}
int main()
{
int byRef = 1;
int byVal = 5;
func(byRef, byVal);
std::cout << "Passed by reference: " << byRef << std::endl;
std::cout << "Passed by value: " << byVal << std::endl;
return 0;
}
You should easily be able to see why the output is: