+ 1

please someone explain the output of this question.

int x(int &a, int &b) { a=3; b=4; return a+b; } int main() { int a; int b= 7; int c=x(a,a); cout<<a<<b<<c; return 0; }

20th Jul 2017, 3:34 PM
Himanshu Bakshi
Himanshu Bakshi - avatar
3 Respuestas
+ 1
To my mind, it will output 478. Why ? Quite difficult : int main(){ int a; int b=7; int c=x(a,a);//oh oh, the same variable for two parameters... To execute the expression 'c=x(a,a)', x(a,a) needs to be executed. a is passed by reference (in function 'x(int& a, int& b)' 'a' and 'b' will be another name for the parameter(s) here 'a'). So EVERY change on 'a' or 'b' is APPLIED on the parameter(s) (here, 'a'). So this is what happen in x(int&, int &); a=3;//Same as 'a=3' BE CARREFUL think about 'a' in the main() and 'a' in x(int&, int&). b=4;//Same as a=4 so a=4. return a+b;//Same as a+a 4+4 It returns 8. so c=8 and a=4 and b has never changed : b=7. I know this code is complicated, if anyone has more question, ask ! (I don't know if I will bé able to answer but I can try !)
20th Jul 2017, 4:50 PM
Jojo
0
bro u were awesome....i was now able understand properly...after a whole lot of struggle.....
20th Jul 2017, 5:20 PM
Himanshu Bakshi
Himanshu Bakshi - avatar
0
wow cool glad I could help you
20th Jul 2017, 5:22 PM
Jojo