关于i++的``side effects''

前些天,碰到一个在考博同学问到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,至于为什么,上面看懂了自然知道。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值