简体   繁体   English

C中的逗号运算符和赋值的评估顺序是否可预测?

[英]Is the order of evaluation with comma operator & assignment in C predictable?

Recently cppcheck raised an error in some C code, that has the structure: 最近cppcheck在一些C代码中引发了一个错误,它具有以下结构:

((void)(value_prev = value), value = new_value())

In most cases this can be split onto 2 lines, however there are some cases this is useful to have in a single statement. 在大多数情况下,这可以拆分为2行,但是在某些情况下,这在单个语句中很有用。

In practice I found this works with popular compilers (GCC/Clang/MSVC), which don't give any warnings (even with warning levels set to their highest) . 在实践中,我发现这适用于流行的编译器(GCC / Clang / MSVC),它们不会发出任何警告(即使警告级别设置为最高)


Example code: 示例代码:

#include <stdio.h>

int get_next(int i);

int main() {
    int i = 0, i_prev = 10;
    do {
        printf("%d\n", i);
    } while ((void)(i_prev = i),
             (i = get_next(i)) != 10);
}

CppCheck 1.73 (latest at time of writing) gives an error with this code: CppCheck 1.73 (撰写本文时的最新版本)给出了以下代码的错误:

(error) Expression '(void)(i_prev=i),(i=get_next(i))!=10'
depends on order of evaluation of side effects`

While the code could be changed to quiet the warning, is the order really undefined? 虽然代码可以更改为安静警告,但订单是否真的未定义?

The order is defined, because there is a sequence point between them. 定义了顺序,因为它们之间存在序列点。 See ISO/IEC 9899 6.5.17: 见ISO / IEC 9899 6.5.17:

The left operand of a comma operator is evaluated as a void expression; 逗号运算符的左操作数被计算为void表达式; there is a sequence point after its evaluation. 评估后有一个序列点。 Then the right operand is evaluated; 然后评估右操作数; the result has its type and value. 结果有它的类型和价值。 95) If an attempt is made to modify the result of a comma operator or to access it after the next sequence point, the behavior is undefined. 95)如果尝试修改逗号运算符的结果或在下一个序列点之后访问它,则行为未定义。

They then give an explicit example: 然后他们给出一个明确的例子:

In the function call 在函数调用中
f(a, (t=3, t+2), c)
the function has three arguments, the second of which has the value 5. 该函数有三个参数,第二个参数的值为5。

I'm not entirely sure why CppCheck is flagging it. 我不完全确定为什么CppCheck会标记它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM