宏和后增量 [英] Macros and postincrement

查看:96
本文介绍了宏和后增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我希望有人可以阐明的一些更奇怪的宏行为:

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

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

  printf("%d %d %d\n",a,b,MAX(a++,b++));
}

输出为4 65.b的值增加两次,但在MAX显示其值之前不增加.有人可以告诉我为什么会这样吗,以及人们如何预测这种行为? (为什么要避免使用宏的另一个实例!)

解决方案

宏进行文本替换.您的代码等效于:

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

这具有未定义的行为,因为b可能会递增(在第三个参数的末尾),然后再使用(在第二个参数中)而没有中间的顺序点.

但是与其他UB一样,如果盯着它看一会儿,您也许可以对您的实现实际上所做的工作做出解释,以产生所看到的结果.参数的评估顺序是不确定的,但在我看来,参数似乎是按从右到左的顺序进行评估的.因此,首先,ab递增一次. a不大于b,因此b再次递增,并且条件表达式的结果为5(也就是说,b在第一次递增之后,在第二次递增之前).

这种行为不可靠-另一实现或另一天的同一实现可能由于以不同顺序评估参数而产生不同的结果,或者理论上甚至可能由于序列点问题而崩溃.

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;

  printf("%d %d %d\n",a,b,MAX(a++,b++));
}

The output is 4 6 5. The value of b is incremented twice but not before MAX displays its value. Can anybody please tell me why this is happening and how does one predict such behavior? (Another instance of why macros should be avoided!)

解决方案

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.

这篇关于宏和后增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆