I was expecting this code snippet to print 3 as the if condition is false and y++ will execute, but it prints 2, any idea why..Thanks!!
int x = 3;
int y = 2;
printf("%d\n", (x<y) ? x++ : y++);
// This prints 2
I was expecting this code snippet to print 3 as the if condition is false and y++ will execute, but it prints 2, any idea why..Thanks!!
int x = 3;
int y = 2;
printf("%d\n", (x<y) ? x++ : y++);
// This prints 2
x++ and y++ are post-increment. That is, they return the current value of the variable, then add one to it.
Pre-increment would be ++x or ++y. Those increment and then return the new value.
Both pre- and post-increment (and -decrement) are useful things when writing loop controls, which is why C supports both.
(Originally, if I remember correctly, C only supported pre-increment and post-decrement, because there happened to be instructions on the machines it was developed on which encapsulated those behaviors. But as C moved to other systems, and as people started noticing that they wanted both pre and post for both, this was generalized.)
Note that this means the c++ language was misnamed. It should have been called ++c -- we want it improved before we use it, not after!
It's because y++ returns the value of y then increases it.
Where as if you put ++y it would increase the value of y first then return it.
The ++ operators are evaluated last; this is called "post-increment." So, this:
int x = 3;
int y = 2;
printf("%d\n", (x<y) ? x++ : y++);
is equivalent to this:
int x = 3;
int y = 2;
printf("%d\n", (x<y) ? x : y);
y++;
(x++ isn't ever reached because of the ternary condition.) On the other hand, this:
int x = 3;
int y = 2;
printf("%d\n", (x<y) ? ++x : ++y);
would increment y before returning its respective value to printf(), so the logic would be:
printf("%d\n", (3<2) ? 3 : 3); // prints 3
Since you use a post increment y++, value of y will be used first and incremented. That is the printf will be passed the value before increment operation, in your case y is 2 before increment and 2 will be printed.
You should consider x++ and y++ after all the other operations of this line have been completed. So, print y and then increment x and y.