我有一个C语言的小代码
#include<stdio.h>
int main()
{
int a=10,b;
b=a++ + ++a;
printf("%d,%d,%d,%d",b,a++,a,++a);
return 0;
}
Turbo C 给出以下输出(如预期的那样)
22,13,13,13
但是 GCC(在 windows 中使用 ubuntu 和代码块编译器)给出了以下内容
22,13,14,14
我相信 Turbo c 输出是正确的,但 GCC 怎么会返回不同的输出?
他们都是对的!这是未定义的行为,因为您不允许在单次调用中多次更改相同的值。
来自 c99 ISO/IEC 9899:TC3 -> 附录 J:
J.2 Undefined behavior
1 The behavior is undefined in the following circumstances:
[...]
— Between two sequence points, an object is modified more than once, or is modified
and the prior value is read other than to determine the value to be stored (6.5).
编辑:
关于告诉 turbo c 早于 c99 的 icepacks 评论,我还添加了来自
C89 标准程序设计语言 C, X3.???-1988:
A.6.2 Undefined behavior
The behavior in the following circumstances is undefined:
[..]
- An object is modified more than once, or is modified and accessed other than to determine the new value, between two sequence points (3.3).