Macros and postincrement

后端 未结 8 1941
庸人自扰
庸人自扰 2020-12-02 02:13

Here\'s some more weird macro behavior I was hoping somebody could shed light on:

#define MAX(a,b) (a>b?a:b)

void main(void)
{
  int a = 3, b=4;

  print         


        
8条回答
  •  情话喂你
    2020-12-02 02:54

    Macros do text substitution. Your code is equivalent to:

    printf("%d %d %d\n",a,b, a++ > b++ ? a++ : b++);
    

    This has undefined behavior, because b is potentially incremented (at the end of the third argument) and then used (in the second argument) without an intervening sequence point.

    But as with any UB, if you stare at it for a while you might be able to come up with an explanation of what your implementation has actually done to yield the result you see. Order of evaluation of arguments is unspecified, but it looks to me as though the arguments have been evaluated in right-to-left order. So first, a and b are incremented once. a is not greater than b, so b is incremented again and the result of the conditional expression is 5 (that is to say, b after the first increment and before the second).

    This behavior is not reliable - another implementation or the same implementation on another day might give different results due to evaluating the arguments in a different order, or theoretically might even crash because of the sequence point issue.

提交回复
热议问题