Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Why would I want to swap the same var with itself?


Assume you had a sorting algorithm that swaps values, and in some cases would swap two of the same values. It's easier (and often faster, thanks to the high cost of branch misprediction) to simply assume the swap of something with itself is a no-op than to explicitly check the address of the value to make sure it isn't the same. Or you could have just forgotten to make the check, and allowed the user to pass in their own swap functions (say, to deep-copy structs in C).


Your code should be robust enough to provide an intuitive default behavior for corner cases like that. That way the application code doesn't need to be cluttered with special conditions.


You wouldn't, but let's say you wrote a function with the signature

  fast_swap_values(unsigned long*, unsigned long*)
Users of the function could accidentally pass in the same addresses.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: