潜在问题在"交换两个变量值,而无需使用第三个变量" [英] Potential Problem in "Swapping values of two variables without using a third variable"
问题描述
我最近沿此方法来对交换两个变量的值,而无需使用第三变量
A ^ = B ^ = a ^ = B
但是,当我尝试了不同的编译器上面的code,我得到了不同的结果,有的给了正确的结果,有些却没有。
什么是可怕的错误与code?
什么是可怕的错误与code?
块引用>是的!
A ^ = B ^ = A ^ = B
实际上调用未定义行为的C和C ++中,因为你正在试图更改在
两个以上的序列点之间的一次。试着写(尽管并非万无一失)
A ^ = B;
b ^ =一;
一个^ = B;而不是
A ^ = B ^ = a ^ = B
。P.S :切勿试图交换两个变量的值,而无需使用第三个。始终使用第三个变量。
修改
由于 @caf 注意到
B ^ = a ^ = B
细纵然^ =
运营商是不确定的,因为的所有访问b
恩pression内被用来计算正在被存储在b
终值,该行为被明确定义。I recently came along this method for swapping the values of two variables without using a third variable.
a^=b^=a^=b
But when I tried the above code on different compilers, I got different results, some gave correct results, some didn't.
Is anything terribly wrong with the code?
解决方案Is anything terribly wrong with the code?
Yes!
a^=b^=a^=b
in fact invokes Undefined Behaviour in C and in C++ because you are trying to change the value ofa
more than once between two sequence points.
Try writing (although not foolproof )
a ^= b; b ^= a; a ^= b;
instead of
a^=b^=a^=b
.P.S : Never try to swap the values of two variables without using a third one. Always use a third variable.
EDIT :
As @caf noticed
b^=a^=b
is fine even though the order of evaluation of arguments of^=
operator is unspecified, since all the accesses ofb
within the expression are being used to compute the final value that is being stored inb
, the behaviour is well defined.这篇关于潜在问题在"交换两个变量值,而无需使用第三个变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!