0

Possible Duplicate:
What’s the side effect of the following macro in C ? Embedded C

What will be the output for the following:

#include <stdio.h>
#define MAN(x,y) ((x) < (y))?(x):(y)
main()
{  
    int i=10,j=5,k=0;
    k= MAN(i++,++j);
    printf("%d %d %d" ,i,j,k);
}

Here i thought that MAN(10,6) will be called and the output will be:

11 6 6

However the output is

11 7 7

Can some one please explain this.

Community
  • 1
  • 1
Nivetha
  • 698
  • 5
  • 17
  • 2
    @chris That's unrelated. We're not adding anything here or assigning `x = x++`. – JJJ Feb 01 '13 at 09:02
  • @Xeo It's *not* the same thing. OP's code is basically `if( i++ > ++j ) { k = ++j; }`. The sequence is well-defined. – JJJ Feb 01 '13 at 09:06
  • Never mind. I forgot there's a sequence point in there. *The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below. 110)* – chris Feb 01 '13 at 09:07
  • @Juhana: Yep, nvm, you're right. – Xeo Feb 01 '13 at 09:11

5 Answers5

4

Remember how macros work.. they replace the text exactly as it is, and do not evaluate their arguements as you would expect functions to do.

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

Is actually

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

This is why j is incremented twice.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

You can simply sub: x <- i++, y <- ++j into your macro define, then you can see that

((i++) < (++j))?(i++):(++j)

i++ and ++j are both executed when doing the comparison; since the comparison returns false, ++j would be executed therefore you got the result

songyy
  • 4,323
  • 6
  • 41
  • 63
0

it becomes

i++ < ++j ? i++ : ++j

i will not be less than j, so we use the second argument

so we do a i++ and ++j and another ++j

so 10 + 1 =11 5 + 1 + 1 = 7 and return the second argument..... 7

11 7 7

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

Since MAN is a macro and not a function, this code:

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

Means this:

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

So, j gets incremented twice: once in the < test, and again when (++j) is evaluated. If MAN were a function and not a macro, the incremented values would be passed, not the expressions themselves, and your answer would be what you expect.

mdunsmuir
  • 492
  • 2
  • 8
0

In macros the it does not calculate the value and pass it just replace the symbol so it becomes some thing like this

MAN(i++,++j) ((i++) < (++j))?(i++):(++j)

so here ++j executes twice and the answer becomes 11,7,7

suresh_knv
  • 46
  • 3