作者wtchen (没有存在感的人)
看板C_and_CPP
标题十三诫增修--08:++i/i++/--i/i--/f(&i)哪个先执行跟顺序有关
时间Thu Jun 9 16:44:17 2016
这篇有争议,乾脆直接重写,看大家认为如何
原标题"在一个运算式中,不能对一个基本型态的变数修改其值超过一次以上"
因为不完全正确(可看以下说明)所以修改
==============================================================
08.
++i/i++/--i/i--/f(&i)哪个先执行跟顺序有关
++i/i++ 和--i/i-- 的问题几乎每个月都会出现,所以特别强调。
当一段程式码中,某个变数的值用某种方式被改变一次以上,
例如 ++x/--x/x++/x--/function(&x)(能改变x的函式)
- 如果Standard没有特别去定义某段叙述中哪个部份必须被先执行,
那结果会是undefined behavior(结果未知)。
- 如果Standard有特别去定义执行顺序,那结果就根据执行顺序决定。
C/C++均正确的例子:
if (--a || ++a) {} // ||左边先计算
if (++i && f(&i)) {} // &&左边先计算
a = (*p++) ? (*p++) : 0 ; // 问号左边先计算
int j = (++i, i++); // 这里的逗号为运算子,表示依序计算
C/C++均错误的例子:
int j =
++i + i++; // undefined behavior,Standard没定义+号哪边先执行
x = x++; // undefined behavior, Standard没定义=号哪边先执行
arr[i] = i++; // undefined behavior, 原因同上
cout << i << "==" << i++; // undefined behavior, Standard没定义哪边先执行
printf( "%d %d %d", I++, f(&I), I++ ); // undefined behavior, 原因同上
foo(
i++, i++); // undefined behavior,这里的逗号是用来分隔引入参数的
// 分隔符(separator)而非运算子,Standard没定义哪边先执行
在C错误但是在C++正确的例子:
C++中,++i/--i为左值(lvalue),i++/i--为右值(rvalue)。
左值可以被assign value给它,右值则不行。
而在C中,++i/--i/i++/i--都是右值。
所以以下的code在C++会正确,C则否。
++++++++++phew ; // C++会把它解释为++(++(++(++(++phew))));
i = v[++i]; // ++i会先完成
i = ++i + 1; // ++i会先完成
补充资料
- Undefined behavior and sequence points
http://stackoverflow.com/questions/4176328/undefined-behavior-and-
sequence-points)
- C11 Standard 6.5.13-17,Annex C
- Sequence poit
https://en.wikipedia.org/wiki/Sequence_point
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 90.41.66.248
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1465461861.A.882.html
1F:→ cgcheng: mulit-thead的话,++就不太是 atomic了啊 06/09 22:13
※ 编辑: wtchen (90.41.66.248), 06/10/2016 15:28:26
※ 编辑: wtchen (90.41.66.248), 06/10/2016 15:29:55
※ 编辑: wtchen (90.41.66.248), 06/10/2016 15:38:14