0

How does this code work(C)?

I got this in challenge today but did not understand how it works? int x = 2, y = 0; int z = (y++) ? 2 : y == 1 && x; printf("%d", z); //Output:1

21st Nov 2019, 5:26 AM
Dhawal Mehta
Dhawal Mehta - avatar
5 Answers
+ 7
First y is initially 0 so due to post increment which has hugest precedence in expression due to parenthesis of ternary so it evaluate first, post increment store value of y first which is 0 is replaced in the parenthesis( y++) place and when y again comes to use it evaluate the increment and value of y will become 1 So expression after first step is int z = 0 ? 2 : 1 == 1 && 2; Now == has highest priority in precedence so it evaluated and 1== 1 so it will return true int z = 0 ? 2 : true && 2; Now && operator has next priority in precedence so && will be evaluated so two non zero and true value return true so return value by && is 1 int z = 0 ? 2 : 1 Now as ternary left to evaluate so it is evaluated as 0 is false so second expression is choose in ternary which is 1 so final output is returned as 1
21st Nov 2019, 6:01 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 3
y++ is 0 so y==1 && x is evaluated. y is 1 now and y==1 is true and x is a positive value so the expression returns 1 since it is both true. Thus the output 1.
21st Nov 2019, 5:50 AM
Avinesh
Avinesh - avatar
+ 3
y++ means use the value first and then increment so it will be 0 when you use it first and will become 1 when you use it 2nd time.
21st Nov 2019, 6:01 AM
Avinesh
Avinesh - avatar
+ 2
Avinesh Thanks for the explaination👍 GAWEN STEASY Thanks, but your explaination is a little confusing.
21st Nov 2019, 6:06 AM
Dhawal Mehta
Dhawal Mehta - avatar
0
Mohammed Niems Go to menu and click copy text.
21st Nov 2019, 6:07 AM
Dhawal Mehta
Dhawal Mehta - avatar