为什么表达式a = a + b - (b = a)在c ++中给出序列点警告? [英] Why does the expression a = a + b - ( b = a ) give a sequence point warning in c++?

查看:253
本文介绍了为什么表达式a = a + b - (b = a)在c ++中给出序列点警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是测试代码:

int main()
{
    int a = 3;
    int b = 4;
    a = a + b - (b = a); 

    cout << "a :" << a << " " << "b :" << b << "\n";    
    return 0;
}

编译此文件时会出现以下警告:

Compiling this gives the following warning:

> $ g++ -Wall -o test test.cpp test.cpp: In function ‘int main()’:
> test.cpp:11:21: warning: operation on ‘b’ may be undefined
> [-Wsequence-point]

为什么操作未定义?

根据我的理解,首先应该评估子表达式(b = a) ),从而设置b = a。然后,由于'+'和' - '具有相同的优先级,表达式将被左相关地评估。因此,接下来应该计算 a + b ,最后应该减去(b = a)的结果 a + b 。我在此处看不到任何序列点规则被违反。

According to my understanding, first the subexpression (b = a) should be evaluated because of higher precedence of (), thus setting b = a. Then, since '+' and '-' have same precedence, the expression would be evaluated left-associatively. Thus, a + b should be evaluated next, and finally the result of (b = a) should be subtracted from a + b. I can't see any sequence-point rule being violated here.

推荐答案

被评估的表达式与完成其副作用之间有区别

There is a difference between an expression being evaluated and completing its side effects.

由于括号的更高优先级,将在减法之前计算 b = a 赋值表达式。它将提供 a 的值作为评估的结果。然而,将该值写入 b 可能无法完成,直到下一个序列点(在这种情况下是完整表达式的结尾)。因此,总表达式的最终结果是未定义的,因为减法可以在赋值之前或之后取 b 的值。

The b = a assignment expression will be evaluated ahead of subtraction due to higher precedence of the parentheses. It will provide the value of a as the result of the evaluation. The writing of that value into b, however, may not complete until the next sequence point, which in this case is the end of the full expression. The end result of the overall expression is therefore undefined, because the subtraction may take the value of b before or after the assignment.

这篇关于为什么表达式a = a + b - (b = a)在c ++中给出序列点警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆