Is there a built in swap function in C?

前端 未结 11 2156
北恋
北恋 2020-12-15 16:01

Is there any built in swap function in C which works without using a third variable?

11条回答
  •  温柔的废话
    2020-12-15 16:18

    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.

提交回复
热议问题