加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:47:15 所属栏目:百科 来源:网络整理
导读:最近cppcheck在一些C代码中引发了一个错误,它具有以下结构: ((void)(value_prev = value),value = new_value()) 在大多数情况下,这可以拆分为2行,但是在某些情况下,这在单个语句中很有用. 在实践中,我发现这适用于流行的编译器(GCC/C++lang / MSVC),它们不
最近cppcheck在一些C代码中引发了一个错误,它具有以下结构:
((void)(value_prev = value),value = new_value())

在大多数情况下,这可以拆分为2行,但是在某些情况下,这在单个语句中很有用.

在实践中,我发现这适用于流行的编译器(GCC/C++lang / MSVC),它们不会发出任何警告(即使警告级别设置为最高).

示例代码:

#include <stdio.h>

int get_next(int i);

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

CppCheck 1.73(撰写本文时的最新版本)给出了以下代码的错误:

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

虽然代码可以更改为安静警告,但订单是否真的未定义?

解决方法

定义了顺序,因为它们之间存在序列点.见ISO / IEC 9899 6.5.17:

The left operand of a comma operator is evaluated as a void
expression; 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.

然后他们给出一个明确的例子:

In the function call
f(a,(t=3,t+2),c)
the function has three
arguments,the second of which has the value 5.

我不完全确定为什么CppCheck会标记它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读