+ 16

a delicious C++ question 4 you😉

What is the output of this code? voidf(int& x){ cout<<x++; x=2; } int main(){ int a=3; int& b=a; f(a); cout<<b; } My answer is 33 but the official answer is 32, why?[ I 'd like to give you a piece of virtual ( void)cake 🍰]

5th Mar 2018, 7:42 PM
Eros boulay
Eros boulay - avatar
8 Answers
+ 19
@ Ace, thank you very much for your good explanation 👍😉
6th Mar 2018, 4:23 AM
tooselfish
tooselfish - avatar
+ 8
Thank you for your detailed answer ,at last I got it😊
5th Mar 2018, 8:04 PM
Eros boulay
Eros boulay - avatar
+ 4
@Ace your explanation is right one point! Here, have some virtual cake ( 🍰).
6th Mar 2018, 9:08 AM
Prasun
Prasun - avatar
+ 4
I'll try to trace what's happening in a way you can understand. Let's keep track of what each variable is and when changes occur. Initially, a = 3 and b's reference points to a. Now f(a) runs... a is still 3 when cout<<a++ runs, as a++ executes after the cout. so a = 3, b references a, so b=3. Then a is changed to 2, and recall that b is a reference to a, so any changes to a affect b. a=2, b=2. The function is over now and b is now printed, so a 2 is outputted to the console. Final result: 32
7th Mar 2018, 5:04 PM
dieserrapha
dieserrapha - avatar
+ 2
void error not mentioning your output is 3 and after that, you added (4) then reassign x to be 2 which is the main function your final answer is 32 https://babasupport.org/printer/hitachi-customer-service/39
6th Mar 2018, 6:01 AM
HITACHISUPPORT
HITACHISUPPORT - avatar
- 1
easy no problem at all
6th Mar 2018, 8:01 PM
Arun
- 1
i want to eat
7th Mar 2018, 5:24 AM
Kunal Kumar
Kunal Kumar - avatar