output ambiguity

kindly somedy explain the output of the following

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

int i=10,j=5,k=0;

k= MAN(i++,++j);
printf("%d  %d  %d \n",i,j,k);

o/p –
12 6 11

This is an effect of using the macros. The compiler will just replace what you have provided it. So let us try to see what is really the code after being processed by the compiler: k = (i++) > (++j) ? (i++) : (++j); To understand why this works, you have to understand the difference between the post increment and the pre increment - in other words the difference between x++ and ++x.

When using the pre increment function, the increment will be done before the actual value will be processed. So you will be processing with the new value x + 1. You have to imagine the ++ before the variable as a function. In fact, one can overload them in C++. The post increment function does similar, except that the value you will be processing will still be x, but in the back, the variable already holds the value x + 1.

Let us write some C++ pseudocode. (int& x just denotes a reference to the variable)

// post(x) is equivalent to x++ 
int post(int& x){
  int old = x;
  x = x + 1;
  return old;

// pre(x) is equivalent to ++x
int pre(int& x){
  x = x + 1;
  return x;

Thus let us substitute the original expression k = (i++) > (++j) ? (i++) : (++j) with our new defined functions. k = (post(i) > (pre(j)) ? (post(i)) : (pre(j)). As we know, this ternary function can also be rewritten in terms of if and else.

if (post(i) > pre(j)){ // here we are comparing 10 with 6, but in the background we already have i = 11 and j = 6. 
   return post(i); // we return 11 here, but in the background the value i is already 12;
} else {
   return pre(j); // won't be called actually

This is why i = 12, j = 6 and k = 11.

1 Like

to me it looks like you made a self defined function and saved it to a header file … so you are writing a statement


and you are calling the MAN function which you saved saved to the library of functions…
the output of the self defined function MAN will go into k and k will print the output of the function you are not giving the body as you made MAN standard library function and included it in your program using a header file