C++ code ( 6 ) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

C++ code ( 6 )

What is the output of this code? intx( int &a, int &b){ a=3; b=4; return a + b; } int main(){ int a=2; int b=7; int c=x(a, a); cout<<a<<b<<c; How to calculate it?

7th Mar 2018, 6:46 AM
Eros boulay
Eros boulay - avatar
6 Answers
+ 12
Hi Alice... The answer is 478. Here is a breakdown of each variable: Variable {a} initializes as 2. The pointer to this variable is then passed to the following method: x(a, a); NOTE: When {b} is assigned the value 4, both {a} and {b} are set to the value 4. This is because both arguments were passed as pointer references to the original variable {a}. The return value is the sum of a + b, which should be 4 + 4, or 8. So, now, {a} in the main() function is 4. The return value of x(a, a) was assigned to variable {c}, which is 8. The variable {b} has not changed and is still 7. Therefore, the final value is: a=4, b=7, c=8 I hope this makes sense.
7th Mar 2018, 7:00 AM
David Carroll
David Carroll - avatar
+ 4
@Freddy: Indeed... this code, as well as, most code in SL challenges, are great models to follow for those seeking to be chronically unemployed. 🤣
7th Mar 2018, 11:58 PM
David Carroll
David Carroll - avatar
+ 2
challenge question, right?
7th Mar 2018, 7:19 AM
‎ ‏‏‎Anonymous Guy
+ 1
@David Caroll Wow...I'm speechless!Now I know how to calculate it,thanks for sharing your knowledge😄
7th Mar 2018, 7:03 AM
Eros boulay
Eros boulay - avatar
+ 1
Nice explanation David :) Outside of this lovely acedemical discussion, I would like to add that I would advise *not* to use a construction like this in real code. To put it mildly: it doesn't approve readability and thus can lead to nasty side effects and bugs. And in this case the good news is that there *is* a predicable outcome, sometimes (especially when you use macros) the outcome isn't even predictable or even defined in the standard and thus compiler specific... You might want to avoid code like that :)
7th Mar 2018, 9:21 PM
Freddy
0
there are many programmer wow nice am new in this field
7th Mar 2018, 12:53 PM
Shah Dost
Shah Dost - avatar