This is question of my midterm exam and it says that I should predict the output. Xcode says that it is 9 4 3, but I do not get how they calculated this and could please help me by giving me a step by step instruction. Thank you!
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void mystery2(int &a, int b, int &c)
{
a = b + c;
b = a + c;
c = a + b;
}
int main() {
int a, b, c;
a = 1;
b = 2;
c = 3;
mystery2(b, c, a);
cout << a << " " << b << " " << c << endl;
}
#include <iostream>
usingnamespace std;
// 2 // 3 // 1
void mystery2(int &a, int b, int &c)
{
cout << "b is " << b << endl; // 3
cout << "c is " << c << endl; // 1
// the value of 4 is retained by a in memory
a = b + c;
cout << "a is " << a << endl;
cout << endl;
cout << "a is " << a << endl; // now a is 4
cout << "c is " << c << endl; // c is 1 still
b = a + c;
cout << "b is " << b << endl; // b is now 5 in the fucntion.
cout << endl;
cout << "a is " << a << endl; // a is still 4
cout << "b is " << b << endl; // b is still 5
c = a + b;
cout << "c is " << c << endl; // c is now 9
cout << endl;
}
int main() {
int a, b, c;
a = 1;
b = 2;
c = 3;
cout << "b is " << b << ", c is " << c << " , a is " << a << endl;
cout << endl;
// i think your confusion is because the variables are switched here.
// input 2, input 3, input 1
mystery2(b, c, a);
// passing by reference means you do not make a copy and you are modifying the value in that memory address
// &a and &c are passed by reference
// b is passed by value
// passing by value means you make a copy inside the function if you do not return the value
// it will go out of scope and is destroyed this gives the impression the value did not change. but you infact did change it.
cout << a << " " << b << " " << c << endl;
}
Thank you very much! I just discovered that while figuring out the output, the logic I applied was correct(and I know passing by value and by reference). But I had absent mindlessly read the statement mystery2(b, c, a) as mystery2(a, b, c), and that's where my fault was. Anyway, Thanks again.
Oh, I am sorry. I did not see that the second parameter is not defined as reference.:) So in main the initial value of b will not be changed, In this case the result will be
a = 4; (the parameter is reference)
b = 2; ( the parameter is value )
c = 9; ( the parameter is reference)