can anyone explain this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

can anyone explain this code?

int a=3,b=4; a+=(-a==1?-3:4); cout<<a; what is the answer and explain it details. thanks 😀

9th Apr 2017, 6:14 PM
Mohd Farees Azuan
Mohd Farees Azuan - avatar
3 Answers
+ 12
Answer is 7 a+=((-a==1)?-3:4); a=a+((-a==1)?-3:4); //assigning a value a=3+((-3==1)?-3:4); // -3 is not equal to 1 so its false a=3+4; a=7
9th Apr 2017, 6:25 PM
Mr.Robot
Mr.Robot - avatar
+ 8
This code prints out 7. On the second line: if -a is equal to 1, then the statement in brackets returns -3, if not it returns 4. Then the return value of the brackets statement is added to the original value of a. In a nutshell: a is equal to 3, -a is equal to -3, which is different from 1. So the 2nd line gives a = a + 4 = 3 + 4 = 7.
9th Apr 2017, 6:22 PM
Aurélien
+ 1
thanks a lot! really helpful
9th Apr 2017, 6:34 PM
Mohd Farees Azuan
Mohd Farees Azuan - avatar