前些天,碰到一个在考博同学问到c++宏定义中传i++表达式参数的问题,虽然觉得这类问题其实没什么意义,但无奈考博题目要考,只好研究了下。
题目是
#include <stdio.h>
#include <stdlib.h>
#define product(x) ((x)*(x))
int main()
{
int i=3,j,k;
j = product(i++);
k = product(++i);
printf("%d,%d",j,k);
return 0;
}
这个问题在TCPL的P51里叫做“side effects”。是这么描述的
Function calls, nested assignment statements, and increment and
decrement operators cause “side effects” - some variable is changed
as a by-product of the evaluation of an expression. Compilers can
interpret this in different ways, and generate different answers
depending on their interpretation. The standard intentionally leaves
most such matters unspecified. When side effects (assignment to
variables) take place within an expression is left to the discretion
of the compiler, since the best order depends strongly on machine
architecture.
因为这种问题最优化顺序依赖于硬件结构,所以标准中故意没有明确定义,交给编译器去决定。上面的结果在gcc,和vs下有不同的结果:
gcc:
12,49
vs:
9,49
下面分析下原因
j = (i++)*(i++);
k =(++i)*(++i) ;
printf(“%d,%d”, j,k);
两者对于k的结果都是一样的,所以k=49=7*7,也就是计算完j之后,i=5,但计算k之前,都先计算了i,固i=7;
即,对于++i,表达式的各项是都计算之后的值。
对于j的结果,在gcc中j=12=4*3,在vs中j=9=3*3。
既,对于i++,在vs中表达式各项都是计算之前的值,*运算符按照基本运算处理。在gcc中,从后往前计算i++。
在gcc中,*运算符按照c函数的参数传递处理。
下面猜测下,
#include <stdio.h>
#include <stdlib.h>
#define product(x) ((x)*(x)*(x))
int main()
{
int i=2,j,k;
k = product(++i);
printf("%d",k);
return 0;
}
结果是80,至于为什么,上面看懂了自然知道。