0

I'm getting some strange values from this macro function written in C

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

which I thought was equivalent to

int func(int x, int y) {
    if (x > y)
        return y;
    else
        return x;
}

However when I run

int x = 10; 
int y = 9;
int z = func(x, y++); 

printf("x=%d, y=%d, z=%d\n", x, y, z);

I get x=10, y=11, z=10 instead of x=10, y=10, z=9

Any idea what's going on here?

potato
  • 49
  • 8
  • `int z = (x > y++) ? y++ : x` condition is false so y is incremented twice. – Mohit Jain Feb 19 '16 at 07:46
  • Write out the macro expansion and read up on undefined behaviour by multiple assignments to the same variable without sequence points between them. – Daniel Jour Feb 19 '16 at 07:47
  • @DanielJour: Where is a variable assigned or altered more than once without intermittent sequence point here? – M Oehm Feb 19 '16 at 07:50
  • 1
    @MOehm I just looked it up and my bad, I didn't knew there's a sequence point after the condition. http://stackoverflow.com/q/10995445/1116364 – Daniel Jour Feb 19 '16 at 07:53
  • @MohitJain That is a duplicate, almost. I cannot vote to close it because it is C++, and this is C. I would if you find a C equivalent, otherwise I think we should keep this question open. – 2501 Feb 19 '16 at 08:09

2 Answers2

5

A macro is just a text-wise expansion. That is:

func(x, y++)

Is replaced with:

(x > y++) ? y++ : x

... when it is a macro. By contrast, when it is a function, the arguments are evaluated once, like:

 int implicit_arg0 = x;
 int implicit_arg1 = y++;
 push implicit_arg0
 push implicit_arg1
 jump to address of "func"

... which causes y to be incremented only once in the function version and twice in the macro.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
1

this is because the macro will be evaluated as (x>y++)?y++:x 10>9 codition is true so it will return y++(but value of y will be 10 since after checking the condition 10>9 y will be incremented to 10) and after returning 10 it will be incremented to 11. hope that helps.