C和C ++之间关于"^ ="的区别操作员 [英] Difference between C and in C++ regarding the "^=" operator

查看:231
本文介绍了C和C ++之间关于"^ ="的区别操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用表达式

*x ^= *y ^= *x ^= *y;

(嗯,我知道这个表情很尴尬,我只想知道区别,没有冒犯性.) 这在C ++中有效,但在C中失败.但是,如果我将其分为三部分,如下所示:

(Well,I know this expression is awkward, and I just want to know the difference, no offense.) This worked in C++, but failed in C. However if I divide it into three parts, like below

*x ^= *y;
*y ^= *x;
*x ^= *y;

两种语言都可以正常工作.

It works fine for both languages.

那么,C和C ++中的运算符^=有什么区别?

So, what are the difference of the operator ^= in C and C++?

推荐答案

区别不在于您最初怀疑的指针,而是评估规则的顺序不同.在新的" C ++ 11 先后顺序规则" 中,我们有:

The difference is not in the pointers as you initially suspected, but in the different order of evaluation rules. In the "new" C++11 "Sequenced-before rules", we have:

内置赋值运算符和所有内置复合赋值运算符的副作用(左参数的修改)在计算左参数和右参数的值(而不是副作用)之后进行排序,并且在赋值表达式的值计算之前(即,在将引用返回修改后的对象之前)进行排序

The side effect (modification of the left argument) of the built-in assignment operator and of all built-in compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments, and is sequenced before the value computation of the assignment expression (that is, before returning the reference to the modified object)

(来自 cppr .)此规则保证了所需的左评估您的表情.

(From cppr.) This rule guarantees the desired right-to-left evaluation of your expression.

与此相反,C和C ++ 98使用序列点" .由于long语句中没有序列点,因此您可以对指针所指向的值进行多次无序列修改,从而调用未定义行为.

In contrast to this, C and C++98 use "Sequence points". Since there are no sequence points in the long statement, you have multiple unsequenced modification of the values the pointers point to and thus invoke Undefined Behavior.

对于C语言,gcc会对此(实时)发出警告.对于C ++ 98,它显然已经使用了新规则,这很好,因为未定义行为是未定义的.

For C, gcc warns about this (live). For C++98 it apparently uses the new rules already, which is fine because undefined behavior is undefined.

拆分语句当然可以解决此问题,因为语句的末尾显式地在需要它们的地方引入了序列点.它也具有优越性,因为它更具可读性,并且无需知道排序规则即可确定代码是否正确.

Splitting the statement solves this problem of course because the end of the statement explicitly introduces sequence points where you need them. It is also superior because it is more readable and one does not need to know sequencing rules to determine whether or not the code is correct.

供参考:此处

这篇关于C和C ++之间关于"^ ="的区别操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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