c - 在同一语句中使用多个递增/递减

标签 c standards increment undefined-behavior operator-precedence

我知道 C 中的计算顺序并不严格,所以表达式 --a+++a 的值是未定义的,因为不知道语句的哪一部分先运行。

但是,如果我知道在特定情况下计算顺序无关紧要怎么办?例如:

  1. 所有修改对应不同的变量(如a[p1++] = b[p2++])
  2. 顺序无关紧要,如 a+++++a - 无论 + 的哪一侧先计算,结果都是二。是否保证在运行另一个部分之前会完全计算其中一个部分? IE。编译器无法记住 a++ 的结果,++a 的结果然后先应用 a++,得到一个而不是两个?例如,缓存 a 的初始值并将其作为参数独立传递给两个运算符。

我对有关 C、C99、C11、C++03 和 C++11 的答案很感兴趣,如果它们之间有任何区别的话。

最佳答案

标准说:

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. /26/

Except as indicated by the syntax /27/ or otherwise specified later (for the function-call operator () , && , || , ?: , and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

所以:

1.) a[p1++] = b[p2++]:保证语句被正确求值并给出预期结果。这是因为每个变量只被修改一次,结果不依赖于两个变量的实际增量完成的时间。

2.) a+++++a:不能保证在 a 第二次使用之前执行副作用(增量)。因此,此表达式可以给出值 a + (a+1)(a+1) + (a+1)a + (a+2 ) 取决于您的编译器何时执行原始变量的副作用增量。

关于c - 在同一语句中使用多个递增/递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22170389/

相关文章:

C 开关语句

c - 将标准输出重定向到套接字

c++ - 为什么在 C++ 中没有强制内联的标准方法?

C90 复合文字

c - 为什么增量运算++a++ 不起作用,至少在 C 中是这样?

java - 在 switch 语句中增加 Java 中的变量?

c - scanf 接受 int 但仅在输入另一个 char/int 并按 enter 后才继续执行

c - 如何在循环中使用管道,我的正确吗?

http - 网址中的空格?

c++ - 我如何自动递增每个类对象?