gpt4 book ai didi

c - `a++ & f(a)` 是未定义的还是未指定的?

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:43 25 4
gpt4 key购买 nike

这是来自 Deep C 的示例(幻灯片 194)

int a = 41;
a++ & printf("%d\n", a);

演示文稿声称结果未定义。为什么? a 仅在序列点之间分配一次。我认为 a++printf 之间的执行顺序是未指定的,因此这将在所有符合标准的编译器上打印 41 或 42,没有未定义的行为。

最佳答案

在这一行 - a++ & printf("%d\n", a); 只有一个序列点(不计算函数参数中发生的事情 - 因为 a++ 1 发生在这一行本身) - 在单个序列点内修改变量并同时从中读取是 UB。如果从对象中读取了先前的值但也有修改,则行为未定义,如 i * i++

&& 是序列点,& 不是序列点,如果那是您感到困惑的地方。

一个序列点是一个尘埃落定的时间点,到目前为止看到的所有副作用都保证是完整的。 C标准中列出的序列点是:

at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression); at the ||, &&, ?:, and comma operators; and at a function call (after the evaluation of all the arguments, and just before the actual call).

标准规定

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

关于c - `a++ & f(a)` 是未定义的还是未指定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19564390/

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