Both are bad ways to attempt to swap two variables. If a
and b
are of some unsigned type, the first might work correctly in all cases (I haven't taken the time to confirm that). If they're both of some signed type, the first risks integer overflow, which has undefined behavior. If they're both of floating-point type (nothing in the question indicates that they aren't), the first risks both overflow and loss of precision, and will not handle infinities and NaNs correctly. If they're of complex type -- well, let's just assume they aren't, and that they're both of the same type.
The second has undefined behavior for any type, since it reads and modifies the value of a
without an intervening sequence point. In the terms used by the C11 standard, the read and write of a
are unsequenced; neither depends on the other, so they can occur in either order. (The result is not limited to the possible orders; the behavior is explicitly completely undefined.)
You're asking (I think) about the run-time efficiency of the two code snippets. The efficiency of incorrect code does not matter.
The way to swap two objects is to use a temporary:
const SOME_TYPE old_a = a;
a = b;
b = old_a;
where SOME_TYPE
is the type of a
and b
. Silly tricks like the one in the question, or the xor trick, are a waste of time.