gpt4 book ai didi

c - C中三元运算符的评估顺序

转载 作者:行者123 更新时间:2023-12-04 01:10:10 25 4
gpt4 key购买 nike

我知道根据标准,应该避免使用 fun(++a, a),因为第二个参数没有明确定义。

但是,这个配方安全吗:

(++a ? a : 10);

我测试了这个代码片段,它按预期工作,对于 a = -1 它的计算结果为 10,对于任何其他 a 它的计算结果为 a+1。这是在标准中明确定义的,还是很大程度上取决于编译器?

最佳答案

这是明确定义的。

在三元表达式中,首先计算第一部分。然后根据该值, 评估第二部分或第三部分。所以 ++a 保证在 a 可能被求值之前被求值。

这在 C standard 的第 6.5.15p4 节中有解释。 :

The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand(whichever is evaluated), converted to the type described below.

关于c - C中三元运算符的评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65109494/

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