Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built in swap function in C?

Tags:

c

swap

People also ask

Is there any inbuilt function for swap in C++?

swap() in C++ The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables.

Why swap function is not working?

You need to pass the memory address reference of the values so that the operation is done on the memory address of the original values. Swap needs to accept the memory reference of the values and store them in pointers which will perform operations to the original values' memory location.

What is the use of swap in C?

Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40. So, after swapping the value of var1 will become 40 & value of var 2 will become 20.


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.


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.


There is no such function in standard C.

(In C++ you have std::swap().)


Maybe a macro from this question can be useful for you.