3 ms·
It's not a trick to use XOR to swap variables. XOR is a code pessimization. You should be using std::swap or just use a temporary which generates proper machine
by fwsgonzo 3y ago
It's not a trick to use XOR to swap variables. XOR is a code pessimization. You should be using std::swap or just use a temporary which generates proper machine code. Most instruction sets have exchange which is 1 instruction.
I guess that answers your question. You can swap two integers on x86. See the xchg instruction.
https://www.felixcloutier.com/x86/xchg https://www.felixcloutier.com/x86/xchg
- rzzzt 3y agoI can only get a bunch of MOVs out of Compiler Explorer. It might be because XCHG is also locking?
- fwsgonzo 3y agoThere is a locked version of XCHG that behaves atomically. I believe that if you swap memory locations that lock is implicit, so maybe you are not just swapping registers?
- retrocryptid 3y agostd::swap is C++, not C.
- retrocryptid 3y agoAlso, not everyone uses x86(-64). In the last several years, I've used ARM, RV32 and RV64 as well as X86-64. Sounds like the original poster is painfully aware of platform and compiler differences, and wants to make something as general case as possible. 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.
- ummonk 3y agoYeah I'm not actually implementing anything but I'm curious about the common coding puzzle of "swap two numbers without a third variable" and what that's actually solvable in a non-platform specific way for signed integers given the limitations of what is actually guaranteed by the C standard.
- retrocryptid 3y agoA laudable goal, but keep in mind, neither gcc nor llvm are truly faithful to the c spec. (Though I haven't really studied C17, so maybe they've mended their ways.) I think I might say it like this: the exhibited behaviour of either gcc or llvm and the behaviour described in C11 are not proper subsets of each other. 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)