加加减减有副作用, C/C++er 请小心

早上看《 the c programming language(2nd edition)》  见到有意思的一段(P51):

 

 

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.

函数调用,嵌套赋值语句 和 自增 自减 操作符 导致 “副作用(side effects)”,  一些变量会在某表达式求值的过程中作为副作用改变。

In any expression involving side effects, there can be subtle dependencies on the order in which variables taking part in the expression are updated.

在任何包含副作用(side effects)的表达式里, 变量值 都会  敏感的依赖于表达式加载的顺序 

One unhappy situation is typified by  the  statement   

  一个典型悲剧(unhappy )的实例:

 

   a[i] = i++;

The  question  is  whether  the  subscript  is  the  old  value  of  i   or  the  new.  Compilers  can  interpret this in different ways, and generate different answers depending on their interpretation.

问题是,不论下标是旧还是新值, 不同编译器会有不同的解析(注: 这就是著名的undefined behaviour, 标准不定义, 编译器爱咋咋滴)

随不同的解析生成不同的结果。

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.

C标准故意搞成未定义(unspecified)的。 当给变量赋值的副作用留给编译器决定, 因为编译器会更具机器架构选择最佳的顺序。

 

(The standard does specify that all side effects  on  arguments  take  effect  before  a  function  is  called,)   

C标准有定义的是, 所有的副作用在发生在参数传入函数调用之前 。

The moral is that writing code that depends on order of evaluation is a bad programming practice in any language. Naturally, it is necessary to know what things to avoid, but if you don't know how they are done on various machines, you won't be tempted to take advantage of  a  particular  implementation.

在任何语言中, 写这种依赖编译器解析顺序的代码, 都是不道德的。 自然, 知道避免这些写法很必要, 但如果你不知道这些东西怎么样在不同机器上面完成, 你不会想去获得特定实现的好处。

 

知乎上面也有很多相关的知识,   google   未定义的行为  zhihu.com 好多问题都是相关的。 

 

最后, 渣渣翻译, 鉴定完毕。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值