"Please never use this in any production code. The less we have to think about a piece of code, the better it is. It's a fun thought experiment nevertheless!"
Swapping two Numbers without Temporary Variables
11–20 of 93 posts
Re: Swapping two Numbers without Temporary Variables
#12I remember just after college I applied for a .net job, when I came in for the interview they gave me a paper exam with a bunch of questions on how to do silly little tricks including that one specifically. I didn't take that job.
Bear in mind this is a place building relatively simple web apps... standard line of business stuff. The test was questions like "how many words can you unscramble from these letters" etc.
A majority of the engineers felt the test meant you "knew you were working with smart people". A majority of the code was unmaintainable sludge. (though a few people were extremely talented)
I no longer work there.
Re: Swapping two Numbers without Temporary Variables
#13Re: Swapping two Numbers without Temporary Variables
#14Or, in Python a, b = b, a Or Rust: (a, b) = (b, a);
These aren't algorithms. The language is still doing something under the hood to do the swap.
And then the cpu is doing something under the hood to do whatever the assembly code thought it said.
Re: Swapping two Numbers without Temporary Variables
#15Re: Swapping two Numbers without Temporary Variables
#16Earlier quoted context omitted.
These aren't algorithms. The language is still doing something under the hood to do the swap.
Some people seem to forget that in high-level programming languages, lines of code seldom map 1-to-1 to processor instructions.
Re: Swapping two Numbers without Temporary Variables
#17Now you may wonder whether we can mathematically prove swapping two variavles requires memory of three variables in digital computer...
Re: Swapping two Numbers without Temporary Variables
#18The person that developed this trick is obviously familiar with the Mathematical properties of numbers. But this is the wrong approach from many prospective, including the impact to performance, the potential of under/overflow, and the lack of readability.
Re: Swapping two Numbers without Temporary Variables
#19To deal with overflow the size of variable a needs to be doubled. This trick, if applied correctly, uses the same amounts of memory. Now you may wonder whether we can mathematically prove swapping two variavles requires memory of three variables in digital computer...
Re: Swapping two Numbers without Temporary Variables
#20https://en.wikipedia.org/wiki/XOR_swap_algorithm
Its better in a number of ways, and since each bit is independent, it could actually be faster on really low end/old processors.
Although these days just about any modern OoO processor will just detect swaps (even if there isn't an actual instruction) and the renamer makes it zero cost.