Is there any built in swap function in C which works without using a third variable?
Assuming you want a C solotion, not a C++ one, you could make it a macro, at least using GCC extension to have it generic enough, something like
#define SWAP(x,y) do { \
typeof(x) _x = x; \
typeof(y) _y = y; \
x = _y; \
y = _x; \
} while(0)
beware of tricks like invocations swap(t[i++],i)
; to avoid them, use the address operator &
. And you'll better use a temporary (for integers, there is a famous and useless trick with exclusive-or).
PS: I'm using two local variables _x
and _y
(but I could have used one local variable only) for better readability, and perhaps also to enable more optimizations from the compiler.