output

Please explain the output of following code:
1
2
3
4
5
6
7
8
#include<stdio.h>
int main()
{
int i=10;
int j=5;
int k=0;
k==(i++)>(++j)?(i++):(++j);
cout<<i<<" "<<j<<" "<<k;


Output: 11 7 0
Why the j is 7?
closed account (Dy7SLyTq)
because ++ increments the variable by one. so j in incremented by one at >(++j) and :(++j)
In the expression k == i++ > ++j ? i++ : ++j, i++ > ++j is evaluated first and returns true because 10 > 6. Now, i holds 11 and j holds 6. Since k holds zero (or false), k == true yields false. Therefore, ++j is executed, and i, j, and k hold 11, 7, and zero, respectively.
Last edited on
I think that the program contains a typo in the following statement

k == (i++)>(++j)?(i++):(++j);

Maybe there should be

k = (i++)>(++j)?(i++):(++j);

If to consider the statement with the typo then the order of calculations is the following

1) i++ > ++j (result is true )
2) k == true ( result is false because k is equal to 0)
3) as the result of previous calculations is false then the following expression is

(++j )

So
1) j will be equal to 7 (it was two times increased)
2) i will be equal to 11 (it was only one time increased)
3) k will not be cjanged.

So you will get

11 7 0

Last edited on
Topic archived. No new replies allowed.