Advertisement

swapping int numbers

Started by August 29, 2001 11:41 AM
2 comments, last by capn_midnight 23 years, 5 months ago
we all know the simple swap function: void swap(int &num1, int &num2) { int temp; temp=num1; num1=num2; num2=temp; } fine and dandy. Just one problem, it declares an extra variable (temp). How do you swap the numbers without that extra variable and, this is a big one, WITHOUT OVERFLOW? I remember seeing something about this one time. If you weren''t worried about overflow, you could do it like this: num1+=num2; num2=num1-num2; num1-=num2; I seem to remember something about ORs and XORs...

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
Advertisement
Make sure you are not swapping the same variables or you will screw the XORings
If you want to write a function for it, declare it as inline.

You could use some inline assembly:

mov EAX, First
xchg EAX, Second
mov First, EAX

This topic is closed to new replies.

Advertisement