Switch Variable Values

vckicks 0 Tallied Votes 155 Views Share

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
William Hemsworth 1,339 Posting Virtuoso

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;
}
mr_ng67 0 Newbie Poster

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

maryann2076 0 Newbie Poster

smple for this

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.