6

One of my friend showed me this program and asked me why is i variable getting incremented twice.

According to my understanding MAX(i++, ++j); in this line i is first send as a parameter and then incremented, so if the initial value of i is 10 then the incremented value should be 11, but it shows the incremented value of i as 12.

Program :

#include<stdio.h>

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

void main(void)
{
    int i = 10;
    int j = 5;
    int k = 0;

    k = MAX(i++, ++j);

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

Output :

12 6 11

Can someone please explain me how is the value incremented to 12 ?

Thanks.

Searock
  • 5,828
  • 9
  • 59
  • 97

8 Answers8

8

MAX is a macro, not a function. In your use case, it expands to:

k = (i++) > (++j) ? (i++) : (++j);
Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
6

Your macro substitution means that you write (i++)>(++j)?(i++):(++j).

David Heffernan
  • 587,191
  • 41
  • 1,025
  • 1,442
5

Your macro definition contains the arguments twice

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

Which makes

 k = MAX(i++, ++j);

expand to

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

And thus, increments twice.

rubenvb
  • 72,003
  • 32
  • 177
  • 319
4

MAX is not a function. i is not send as a parameter.

MAX is a macro. It is text-replaced where it's used:

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

Now you know why it is incremented twice.

Didier Trosset
  • 34,718
  • 13
  • 85
  • 119
2

Macro do simple text substitution, so after macro expansion, the k = MAX(i++, ++j); line is seen by the compiler as :

k = (i++)>(++j)?(i++):(++j);
Sylvain Defresne
  • 40,235
  • 11
  • 72
  • 82
2

Your MAX macro expands to

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

showing why you get a double increment.

gspr
  • 10,861
  • 3
  • 41
  • 72
2

The macro will be expanded to something like in pseudo-C code :

if( i++ > j++)  // i is incremented the first time,  j is incremented once
   return i++;  // i is incremented the second time
else
   return j++;  // we never go there, so j is not incremented twice
Xavier T.
  • 39,000
  • 8
  • 66
  • 95
1

When using MAX(i++, ++j), the generated code will be :

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

Using preprocessor macro just expand the code and copy/paste the arguments in place. You might want to use a function for this case.

int max(int x, int y)
{
  return (x > y ? x : y);
}

Modern compiler will inline it while respecting the original behavior of the function call.

BenMorel
  • 31,815
  • 47
  • 169
  • 296
Nekresh
  • 2,868
  • 22
  • 28