为什么这个语句不适用于java x ^ = y ^ = x ^ = y; [英] Why is this statement not working in java x ^= y ^= x ^= y;

查看:207
本文介绍了为什么这个语句不适用于java x ^ = y ^ = x ^ = y;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int x=1;
int y=2;
x ^= y ^= x ^= y;

我期待交换价值。但它给出x = 0和y = 1。
当我尝试用C语言时,它给出了正确的结果。

I am expecting the values to be swapped.But it gives x=0 and y=1. when i tried in C language it gives the correct result.

推荐答案

你的陈述大致相当于这个扩展的形式:

Your statement is roughly equivalent to this expanded form:

x = x ^ (y = y ^ (x = x ^ y));

与C不同,在Java中,二进制运算符的左操作数保证在右边之前进行求值操作数。评估如下:

Unlike in C, in Java the left operand of a binary operator is guaranteed to be evaluated before the right operand. Evaluation occurs as follows:

x = x ^ (y = y ^ (x = x ^ y))
x = 1 ^ (y = 2 ^ (x = 1 ^ 2))
x = 1 ^ (y = 2 ^ (x = 3))
x = 1 ^ (y = 2 ^ 3)             // x is set to 3 
x = 1 ^ (y = 1)
x = 1 ^ 1                       // y is set to 1
x = 0                           // x is set to 0

您可以反转每个xor表达式的参数顺序,以便在再次计算变量之前完成赋值: / p>

You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:

x = (y = (x = x ^ y) ^ y) ^ x
x = (y = (x = 1 ^ 2) ^ y) ^ x
x = (y = (x = 3) ^ y) ^ x 
x = (y = 3 ^ y) ^ x             // x is set to 3
x = (y = 3 ^ 2) ^ x
x = (y = 1) ^ x
x = 1 ^ x                       // y is set to 1
x = 1 ^ 3
x = 2                           // x is set to 2

这是一个更紧凑的版本,也适用:

This is a more compact version that also works:

x = (y ^= x ^= y) ^ x;

但这是交换两个变量的真正可怕方式。使用临时变量是一个更好的主意。

But this is a truly horrible way to swap two variables. It's a much better idea to use a temporary variable.

这篇关于为什么这个语句不适用于java x ^ = y ^ = x ^ = y;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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