Ask HN: Is it possible to swap two signed integers in C without a third variable
The standard tricks of using arithmetic or xor don't work because both have potentially undefined behavior on some values of signed integers.
If sizeof(int) were guaranteed to be sizeof(unsigned int) then maybe a cast could do it: (unsigned int )&a = (unsigned int )&a ^ (unsigned int )&b; (unsigned int )&b = (unsigned int )&a ^ (unsigned int )&b; (unsigned int )&a = (unsigned int )&a ^ (unsigned int )&b;
What would be a general solution? Is there a way to use the preprocessor to spit out sizeof(int) lines that do bitwise xor on every respective byte in a and b?
9 comments
[ 2.9 ms ] story [ 39.8 ms ] threadI guess that answers your question. You can swap two integers on x86. See the xchg instruction.
https://www.felixcloutier.com/x86/xchg
I mean sure, this seems like a pretty out-there corner case, but maybe they want to support the Bendix G-15 and other 1's complement machines.
This whole exercise got me thinking if there's an architecture supported by gcc where unsigned {short, int, long, long long} and {short, int, long, long long} have different widths. (even though it's not mandated by the spec)
I'm sure you could do it byte by byte and hope the compiler could optimize it.
(I don't have the C17 spec around, so maybe someone else could check it didn't add that constraint, in which case my response would be "Of course! just use C17!")