0

The xor operator allows you to switch the values of two integer variables without the need for a third, temporary variable.

int int1 = 56;
int int2 = 72;

int1 = int1 ^ int2;
int2 = int1 ^ int2;
int1 = int1 ^ int2;

//or
// int1 ^= int2;
// int2 = int1 ^ int2;
// int1 ^= int 2;

//int1 will be equal to 72
//int2 will be equal to 56
4
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by maryann2076
0

There are many reasons not to use that, a couple of reasons are:
- It only works on integers
- It fails if it tries to swap two variable both pointing to the same integer

For example, it would fail here:

void Swap(int &a, int &b) {
	a ^= b;
	b ^= a;
	a ^= b;
}

int main() {
	int a = 4;
	int &b = a;

	Swap(a,b);
	cout << a;
	return 0;
}
0

would be it the same as:

int1 = int1 + int2
int2 = int1 - int2
int1 = int1 - int2

no need in third variable and it works for none integers also

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.