-3

Using define preprocessor directive why following program outputs 4 instead of 3?

#include <stdio.h>
#define MAX(A,B)((A)>(B)) ? A : B

int max_t(int a, int  b)
{
  return ((a)>(b)) ? a : b; 
}

int main()
{
  int i=1;
  int j=2;
  int val = MAX(++i, ++j); // this outputs 4 but why?
  //int val = max_t(++i, ++j);
  printf("%d\n", val);
  return 0;
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tushar
  • 481
  • 6
  • 26

2 Answers2

7

Macros are just replacements by tokens so

MAX(++i, ++j);

expands to

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

As you see the parameters are evaluated (and incremented) twice in this case and therefore the output is 4.

Osiris
  • 2,783
  • 9
  • 17
3
 int main()
 {
   int i=1;
  int j=2;
  int val = ((++i)>(++j)) ? ++i : ++j;

   printf("%d\n", val);
  return 0;
 }

This is what happening after preprocessor stage (After Macro expansion) and you can check this by "cc -E file.c -o file.i" command in linux gcc compiler , this expanded code is at last of the file .

so here : val = (2 > 3 ? 3 : 4 ) , this 4 get stored into val , thats why val = 4.

new_learner
  • 131
  • 10