Swap two variables values
Let's say that we have two variables a
and b
and we want to swap their values:
int a = 5;
int b = 9;
In a classical fashion we usually use an temporary tmp
variable to help us do the trick:
int tmp = a; // tmp = 5
a = b; // a = 9
b = tmp; // b = 5
This is also possible without using tmp
. We only have to do some XOR bit operations:
a = a xor b; // a = 12
b = a xor b; // b = 5
a = a xor b; // a = 9
Read the full article on http://betterexplained.com.
Written by Alex Cristea
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Variables
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#