1

What will be the output of the following code? Online compilers give the result: 12 6 11. Can someone tell me how?

#include<stdio.h>

#define MAX(x,y) (x)>(y)?(x):(y)

main()
{
    int i = 10, j = 5, k = 0;
    k = MAX(i++, ++j);
    printf("%d %d %d", i, j, k);
}

2 Answers2

2

It gets translated to:

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

Now it's easy to tell why..

i++ makes i 11, ++j makes j 6. Now we have:

10 > 6

Which is true, then we return i++, which is 12 now.

Use the -E flag to see the output of the pre-processor.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0
k = MAX(i++, ++j);

This code will be replaced by

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

when checking the condition (i++)>(++j), i is post increment(after the operation it will increment) and j is pre-increment( increment the j and substitute it). so while checking it will take (10) > (6), it is true! after this check i will become 11.

k = (i++)>(++j)?(i++):(++j); --> k = (i++)>(++j)?((11)++):(++j); // note after condition check i becomes 11.
// due to post increment after assigning the value to k, i will be incremented to 12. but the last ++j wont excuted.

So you will get output 12 6 11.

else you can rewrite the k = (i++)>(++j)?(i++):(++j); as

if((i++)>(++j)) //when condition check i=10, j=6 after check i=11,j=6
k=i++; // k= 11++; after assigning 11 to k i will be incremented to 12
else
k=++j; // this wont be executed
Sathish
  • 3,740
  • 1
  • 17
  • 28