Why swap with xor works fine in c++ but in java doesn't ? some puzzle [duplicate]

狂风中的少年 提交于 2019-12-04 04:16:41

By writing your swap all in one statement, you are relying on side effects of the inner a^=b expression relative to the outer a^=(...) expression. Your Java and C++ compilers are doing things differently.

In order to do the xor swap properly, you have to use at least two statements:

a ^= b; 
a ^= (b ^= a);

However, the best way to swap variables is to do it the mundane way with a temporary variable, and let the compiler choose the best way to actually do it:

int t = a;
a = b;
b = t;

In the best case, the compiler will generate no code at all for the above swap, and will simply start treating the registers that hold a and b the other way around. You can't write any tricky xor code that beats no code at all.

That's not guaranteed to work in C++ either. It's undefined behavior.

You should do it in three separate statements:

a ^= b; 
b ^= a;
a ^= b;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!