xor运算符使用引用或指针交换两个变量的值 [英] Interchanging values of two variables by xor operator using references or pointers

查看:110
本文介绍了xor运算符使用引用或指针交换两个变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个整数变量i和j,我想做一个函数,将这两个变量作为参数并使用xor运算符互换它们的内容。现在,如果让函数按值接受参数,即 void swap(int x,int y); (函数主体与函数相同)交换),则可以在函数中很好地交换这些值。但是,正如我想要的那样,是在调用函数中交换变量的值,因此我使用了通过引用(以及通过指针)传递参数的方法:

I have two integer variables i and j and I want to make a function which takes these two variables as its argument and interchanges their contents using xor operator. Now if I make the function to take arguments by value i.e void swap (int x , int y);(with function body same as for the function swap below) then the values are being swapped nicely within the function. But as what I want is the swapping of the values of the variables in the calling function I used passing arguments by reference (and by pointers as well) :

void swap ( int& x , int& y )
{
    x^=y^=x^=y;
    cout << x<< " " << y << endl ;
}

int main ()
{
    int i (1), j (2) ;
    swap ( i, j ) ;
    cout << i << " " << j << endl ;
}

但两种情况均未显示正确的结果!

but neither case showed the correct result !

为什么 swap 函数不交换通过引用或指针传递的参数上的值?

Why is the swap function not swapping the values on passing arguments by reference or pointers ?

推荐答案


我有两个整数变量i和j,我想创建一个函数
,该函数将这两个变量作为参数并互换它们的
内容使用xor运算符。

I have two integer variables i and j and I want to make a function which takes these two variables as its argument and interchanges their contents using xor operator.

为什么?

已经弄清楚了,您需要将指针传递给对象,或使用引用。

As you've figured out, you need either to pass pointers to the objects, or to use references.

此:

x^=y^=x^=y;

具有未定义的行为,因为它在序列点之间两次修改了同一对象(它对两个 x y )。

has undefined behavior, since it modifies the same object twice between sequence points (it does this for both x and y).

如果两个对象都是同一个对象;

The xor trick fails if both objects are the same object; the first xor zeros the object.

如果要交换两个对象,只需使用一个临时对象即可:

If you want to swap two objects, just use a temporary:

int temp = x;
x = y;
y = temp;

这很简单,并且有效

这篇关于xor运算符使用引用或指针交换两个变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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