C 中的表达式求值
为什么下面这段 C 代码会打印 12 12 12
int main(int argc, char const *argv[]) {
int a = 2, *f1, *f2;
f1 = f2 = &a;
*f2 += *f2 += a += 2.5;
printf("%i %i %i\n", a, *f1, *f2);
return 0;
}
Why does the following piece of C code print 12 12 12
int main(int argc, char const *argv[]) {
int a = 2, *f1, *f2;
f1 = f2 = &a;
*f2 += *f2 += a += 2.5;
printf("%i %i %i\n", a, *f1, *f2);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此行具有 未定义行为,因为您更改了
*f2
(即a
) 在同一表达式中多次出现,且没有插入序列点。 UB 意味着你的程序可能会打印“Hello World”,它可能会崩溃,它可能会打印12 12 12
或12 12 1029
或者它可能会开始吃掉你的大脑。不要依赖未定义的行为。引用 C++ 标准(我知道问题被标记为 C,但我没有 C 标准,我知道 C 中也有同样的规则)
This line has Undefined Behavior because you change the value of
*f2
(i.e.a
) more than once within the same expression without an intervening sequence point. UB means that your program may print "Hello World", it may crash, it may print12 12 12
or12 12 1029
or it may start eating your brains. Don't rely on undefined behavior.To quote the C++ standard ( I know the question is tagged C, but I don't have a C standard by me and I know the same rule holds in C)
它为所有变量打印出相同的值,因为您只指向一个
int
变量:a
。它打印出
12
因为a + 2.5 = 4
(a
是一个int
),然后添加它对自己两次。@Downvoters:为什么这么消极?我认为我的回答说明了这个编译器在这个示例代码上做了什么,这应该有助于OP理解行为。我同意 Armen Tsirunyan 的答案是正确的(即应该打勾)并且 行为未根据标准。但标准已经实现,我还没有看到编译器编译代码,然后在运行时突然举手并说
未定义的行为!
。It prints out the same value for all because you are only pointing to one
int
variable:a
.It prints out
12
becausea + 2.5 = 4
(a
is anint
), and then you add it to itself twice.@Downvoters: Why so negative? I think my answer says what this compiler is doing on this example code, which should help the OP understand the behaviour. I agree that Armen Tsirunyan's answer is right (i.e. should get the tick) and that the behaviour is undefined according to the standard. But standards are implemented, and I've yet to see a compiler that compiles code and then, at run-time, suddenly throws up its hands and says
Undefined behaviour!
.我因为
*f2
和*f1
指向a
(一个整数)。所以
*f2 = &a = 2
和*f1 = &a = 2
此时,您将值添加到
2.5
(因为a
是一个整数,所以您将获得4
)。比你
现在做的
f2+f1+a = 12。
I because
*f2
and*f1
point toa
(an integer).So
*f2 = &a = 2
and*f1 = &a = 2
At this point you add to a the value of
2.5
(becausea
is an integer, you'll obtain4
).Than you have
At this point you do
f2+f1+a = 12.