0

What is the out of this code?

int a=1,b=1; int c = ++a || b++; int d = b-- && --a; printf("%d %d %d %d",a,b,c,d);

30th Jan 2019, 2:51 AM
Praveen Kumar
Praveen Kumar - avatar
3 Answers
0
EDIT: I am incorrect. When I run the code, the output is "1 0 1 1". Who can solve this mystery?! 1 is short for true. So a and b are both true. Then in the second line, the ++ increases the value of both a and b by 1. However, c is still true because b was increased after it was checked (beacuse ++ is after the variable name) -- and || means true if at least one is true. Then on the third like, both a and b are decreased by 1. However, d is false because b is 2 when it is checked -- and && only returns true is both are true. At the end... a = 1 = true b = 1 = true c = true d = false The printf function joins the arguments/variables into a string (and the first argument is already just a string), so the output should be "%d %d %d %d11truefalse".
30th Jan 2019, 3:18 AM
James
James - avatar
+ 3
James Since "++a" is true there's no need to check for "b++". That way only the value of "a" is increased. In the following code both "a++" and "b++" need to be checked (because of &&), thus the output being 1 1 1 1: int a=1, b=1; int c = ++a && b++; int d = b-- && --a; printf("%d %d %d %d",a,b,c,d);
30th Jan 2019, 4:46 AM
Diego
Diego - avatar
+ 2
James "However, d is false because b is 2 when it is checked" 2 evaluates to true. In fact, any integer but zero evaluates to true.
30th Jan 2019, 4:50 AM
Diego
Diego - avatar