gpt4 book ai didi

c - 为什么此代码打印 1 2 2 而不是预期的 3 3 1?

转载 作者:行者123 更新时间:2023-12-03 18:17:14 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why are these constructs using pre and post-increment undefined behavior?

(14 个回答)


去年关闭。




注意:这是一个自我问答,并且针对“Let us C”一书宣传的错误信息进行了更直观的提问。另外,请保留 出了讨论,这个问题是关于C .
我正在阅读 Yashwant Kanetkar 的书“Let us C”。
书中有如下例子:

#include <stdio.h>

int main(void) {
int a = 1;
printf("%d %d %d", a, ++a, a++);
}
作者声称这段代码应该输出 3 3 1 :

Surprisingly, it outputs 3 3 1. This isbecause C’s calling convention is from right to left. That is, firstly1 is passed through the expression a++ and then a is incrementedto 2. Then result of ++a is passed. That is, a is incremented to 3and then passed. Finally, latest value of a, i.e. 3, is passed. Thus inright to left order 1, 3, 3 get passed. Once printf( ) collects them itprints them in the order in which we have asked it to get themprinted (and not the order in which they were passed). Thus 3 3 1gets printed.


但是,当我编译代码并使用 clang 运行它时,结果是 1 2 2 ,不是 3 3 1 ;这是为什么?

最佳答案

作者错了。不仅函数参数的求值顺序在 C 中未指定,求值之间也没有顺序。雪上加霜的是,在独立表达式中没有中间序列点的情况下读取和修改同一个对象(这里 a 的值在 3 个独立表达式中求值并在 2 个中修改)具有未定义的行为,因此编译器可以自由生成它认为合适的任何类型的代码。
详情见Why are these constructs using pre and post-increment undefined behavior?

关于c - 为什么此代码打印 1 2 2 而不是预期的 3 3 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63505019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com