In: Computer Science
C++ program. Please explain how the code resulted in the output. The code and output is listed below.
Code:
#include <iostream>
#include <string>
using namespace std;
int f(int& a, int b) {
int tmp = a;
a = b;
if (tmp == 0) { cout << tmp << ' ' << a << ' ' << b << endl; }
b = tmp;
return b;
return a;
}
int main() {
int a = 0, b = 1, c = 8;
f(b, c);
cout << a << ' ' << b << ' '
<< c << endl;
a = f(a, b);
cout << a << ' ' << b << ' '
<< c << endl;
return 0;
}
Output:
0 8 8
0 8 8
0 8 8
int &a is the reference variable, which means its an another variable for an already existing variable.
Function | Main |
int f(int& a, int b) { 8. if (tmp == 0) { cout << tmp << ' ' << a << ' ' << b << endl; } 9. b = tmp; |
int main() { 2. f(b, c); 4. a = f(a, b); return 0; |
variable a = 0, b = 1, c = 8
line 2: is calling function f(b,c)
line 6: tmp = 1 (a value is 1)
line 7 : a=8 (b is having 8 value) note : a is reference variable which is referencing b in main, so a value reflect in b.
line 8 : will not execute..(if condition is false)
line 9: b=1 (tmp is having 1 value)
line 10: return
line 3: print a , b , c [a is having 0, b is having 8(because of line 7) and c is having 8]
line 4: is calling a = f(a, b)
line 6: tmp = 0 (a value is 0)
line 7 : a=8 (b is having 8 value) note : a is reference variable which is referencing 'a' in main, so 'a' value reflect in 'a' of main.
line 8 : print tmp , a , b [tmp is having 0, a is having 8 and b is having 8 ](if condition is true)
line 9: b=0 (tmp is having 0 value)
line 10: return b
line 4: a = 0 (function returned 0 )
line 5: print a , b , c [a is having 0, b is having 8(updated by previous function call) and c is having 8]