Is there a built in swap function in C?

No.
C++ builtin swap function: swap(first,second);
Check this: http://www.cplusplus.com/reference/algorithm/swap/

You can use this to swap two variable value without using third variable:

a=a^b;
b=a^b;
a=b^a;

You can also check this:

https://stackoverflow.com/questions/756750/swap-the-values-of-two-variables-without-using-third-variable

How to swap without a third variable?


Why do you not want to use a third variable? It's the fastest way on the vast majority of architectures.

The XOR swap algorithm works without a third variable, but it is problematic in two ways:

  1. The variables must be distinct i.e. swap(&a, &a) will not work.
  2. It is slower in general.

It may sometimes be preferable to use the XOR swap if using a third variable would cause the stack to spill, but generally you aren't in such a position to make that call.

To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

Tags:

C

Swap