swapNoTemp.cpp
#include <iostream> using namespace std; /** * Swap the parameters. * @param a The first parameter. * @param a The second parameter. */ void swap(int& a, int& b) { int temp = a; a = b; b = temp; } /** * Swap the parameters without a temp variable. * Warning! Susceptible to overflow/underflow. * @param a The first parameter. * @param a The second parameter. */ void swapNoTemp(int& a, int& b) { a -= b; b += a;// b gets the original value of a a = (b - a);// a gets the original value of b } int main() { int a = 100; int b = 500; cout << "a = " << a << " b = " << b << endl; swapNoTemp(a, b); cout << "a = " << a << " b = " << b << endl; return 0; }
This code was developed by me, G. Samaras.
Notice, that I used as little C++ as possible, so that one can easy interchange between C and C++.
Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)
Example for overflow and underflow in void swapNoTemp(int& a, int& b)
@Ronak
Well, prone to overflow and underflow was not the proper phrase. We could say “susceptible to overflow/underflow”.
The line of code that is the one to fear is this
a -= b;
We just need to find an overflow or underflow for this.
And as a respected programmer said to me:
“To do that, choose say, INT_MIN for a and INT_MAX for b (or some other suitable values in between). Of course, it might still be the case that it “works”, but you’re in the realm of implementation defined behaviour.”
However, I decided to change the comment I have in the code, thank you very much for the comment 🙂
Thanks for the Response
Great Logical thinking!
I agree with you, but the idea did not come from me in first place 🙂
Maybe the safer way how to do this is to use XOR, but that approach is definitely the worst readable one:
a = 2 = 0010; b = 6 = 0110
a = XOR(a, b) // a = 4 = 0100
b = XOR(a, b) // b = 2 = 0010
a = XOR(a, b) // a = 6 = 0110
but still it definitely should be over/underflow proof
Hmm interesting..Thank you very much for posting! Why it’s safer?
It’s overflow proof. But according to wiki: https://en.wikipedia.org/wiki/XOR_swap_algorithm, compiler optimization can result in even faster and memory equivalent solution when using extra variable, so I guess thats the best solution so far when you’re not working at assembly level.
PS.: Sorry for late reply, my email notifications are all messed up.
@doomitsa better late than never, thank you!