Please explain the output of the following C Programming


#1

Please explain the output ??

#define MAX(x,y) (x)>(y) ? (x):(y)
#include<stdio.h>

int main() {
int i=10;
int j=5;
int k=0;
k== MAX(i++,++j);

printf("%d,%d,%d",i,j,k);
}

O/P: 11,7,0


#2

It’s quite simple. You just need to remember the precedence of operators.

i=10, j=5, k=0

Now, k==MAX(i++,++j)
-> { k=={ (i++)>(++j) } } ? (i++) : (++j)

See the above parenthesization clearly.

1st { (i++) > (++j) } will be evaluated.
Then {k==(result from above statement will be evaluated), i.e. 0==1}
Now as 0==1 is false, so (++j) will be evaluated

You can clearly see (i++) is evaluated only once and (++j) is evaluated twice.

So value of i, j, k at the end:
i=11
j=7
k=0


#3

Basically, the variable i is incremented using post-increment operator and j is incremented using pre-increment operator . So, the variable i will be incremented in the 1st statement itself while j is incremented in the next statement .So the equality becomes false and hence the incremented value of j will be shown as output in the next step. Since the equality evaluates to false hence k stores the bool value of false as 0.