How to Implement Swap Function in C
- Use Temporary Variable to Implement Swap Function in C
- Use Arithmetic Operations to Implement Swap Function in C
- Use Bitwise XOR Operation to Implement Swap Function in C
- Use Bitwise XOR Operation and Macros to Implement Swap Function in C
This article will explain several methods of how to implement the swap function in C.
Use Temporary Variable to Implement Swap Function in C
The swap function is a typical operation to conduct on variables. There is no C standard library function that provides the feature like C++ has std::swap
function. In this article, we implement swap functions for integral values; namely, most of them take long int
type arguments, but one can always define multiple prototypes for different types and ensure generic features using macro expansions. The following example demonstrates the swap function using the temporary variable. Note that, even though it is the easiest implementation, this one is relatively the fastest version among others listed below (when the compiler optimizations are used).
#include <stdio.h>
#include <stdlib.h>
void swap(long *x, long *y) {
long tmp = *x;
*x = *y;
*y = tmp;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: ./program first_number second_number/n");
return 1;
}
long x = strtol(argv[1], NULL, 0);
long y = strtol(argv[2], NULL, 0);
printf("x:%ld, y:%ld\n", x, y);
if (x != y) swap(&x, &y);
printf("x:%ld, y:%ld\n\n", x, y);
exit(EXIT_SUCCESS);
}
Sample Command:
./program 123 432
Output:
x:123, y:432
x:432, y:123
Use Arithmetic Operations to Implement Swap Function in C
Alternatively, one can implement a swap function using only addition and subtraction operations. We operate on passed pointers in the function, thus, modifying the argument values directly. In the main
function, there is an if
condition before the swap
function is called to avoid invocation when the operands are equal.
#include <stdio.h>
#include <stdlib.h>
void swap(long *x, long *y) {
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: ./program first_number second_number/n");
return 1;
}
long x = strtol(argv[1], NULL, 0);
long y = strtol(argv[2], NULL, 0);
printf("x:%ld, y:%ld\n", x, y);
if (x != y) swap(&x, &y);
printf("x:%ld, y:%ld\n\n", x, y);
exit(EXIT_SUCCESS);
}
Use Bitwise XOR Operation to Implement Swap Function in C
The most tricky and slightly complicated implementation of the swap function is where the bitwise XOR operation is used. Note that this version does not need a third variable like the previous example. At first, we store the XOR-ed result of the given integers in one of their places. Then, we XOR the stored value(y
) with the other integer and store the result in the latter’s place. Finally, both variables are XOR-ed once more time, and the result is stored in the firstly modified variable - y
in this case. This implementation involves more machine code instructions when compiled without optimization flags, thus, yields a more compute-intensive solution.
#include <stdio.h>
#include <stdlib.h>
void swap(long *x, long *y) {
*y = *x ^ *y;
*x = *x ^ *y;
*y = *x ^ *y;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: ./program first_number second_number/n");
return 1;
}
long x = strtol(argv[1], NULL, 0);
long y = strtol(argv[2], NULL, 0);
printf("x:%ld, y:%ld\n", x, y);
if (x != y) swap(&x, &y);
printf("x:%ld, y:%ld\n\n", x, y);
exit(EXIT_SUCCESS);
}
Use Bitwise XOR Operation and Macros to Implement Swap Function in C
As demonstrated in the previous example, the XOR swap function can also be implemented as a function-like macro. Note that there needs to be a check if the two operands are the same object; otherwise, the macro assigns zero to the object, which results in the erroneous output. This check is implemented using ?:
conditional, and only then do we execute the XOR swap algorithm similar to the previous implementation. Mind though, that this function-like macro can only process integral values.
#include <stdio.h>
#include <stdlib.h>
#define XORSWAP(a, b) \
((&(a) == &(b)) ? (a) : ((a) ^= (b), (b) ^= (a), (a) ^= (b)))
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: ./program first_number second_number/n");
return 1;
}
long x = strtol(argv[1], NULL, 0);
long y = strtol(argv[2], NULL, 0);
printf("x:%ld, y:%ld\n", x, y);
XORSWAP(x, y);
printf("x:%ld, y:%ld\n", x, y);
exit(EXIT_SUCCESS);
}
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook