gpt4 book ai didi

c++ - 将递增/递减运算符放在三元/条件运算符中是否安全?

转载 作者:IT老高 更新时间:2023-10-28 12:52:43 26 4
gpt4 key购买 nike

这是一个例子

#include <iostream>
using namespace std;
int main()
{
int x = 0;
cout << (x == 0 ? x++ : x) << endl; //operator in branch
cout << "x=" << x << endl;
cout << (x == 1 || --x == 0 ? 1 : 2) << endl; //operator in condition
cout << "x=" << x << endl;
return 0;
}

输出:

0
x=1
1
x=1

我理解输出,但 这是未定义的行为吗?在这两种情况下都保证评估顺序吗?

即使有保证,我也很清楚使用增量/减量很快就会成为可读性问题。我只是在看到类似的代码并且立即不确定时才问,因为有很多模棱两可/未定义使用递增/递减运算符的示例,例如...

  • C++ does not define the order in which function parameters are evaluated.

    int nValue = Add(x, ++x);
  • The C++ language says you cannot modify a variable more than once between sequence points.

     x = ++y + y++
  • Because increment and decrement operators have side effects, using expressions with increment or decrement operators in a preprocessor macro can have undesirable results.

     #define max(a,b) ((a)<(b))?(b):(a)
    k = max( ++i, j );

最佳答案

对于条件运算符(§5.16 [expr.cond]/p1):

Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

对于逻辑 OR 运算符(§5.15 [expr.log.or]/p1-2):

the second operand is not evaluated if the first operand evaluates to true. [...] If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

您的代码的行为是明确定义的。

关于c++ - 将递增/递减运算符放在三元/条件运算符中是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25725936/

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