In C, the swap function (value exchange) is used to swap the values of variables. For example, given two variables a = 5 and b = 10, using a swap function can change them to a = 10 and b = 5. C++ provides the standard library function std::swap, but C does not have such a built‑in function. Therefore, in C you need to implement the swap function yourself.
Why do you need to write your own swap function in C?
Unlike C++, the C language does not provide a generic swap function in its standard library. Consequently, you need to implement a custom swap function that can be applied to specific data types. Additionally, using pointers allows you to safely exchange variable values via a function.
What you’ll learn in this article
In this article, we explain how to implement a swap function in C and, as an extension, introduce methods for swapping the values of arrays and structs, as well as examples of using it in sorting algorithms. By learning the following topics, you can deepen your understanding of programming in C.
Basic implementation of a swap function
Implementing a swap function using pointers
Swapping values of arrays and structs
Using swap in sorting algorithms
2. Basic Implementation Methods for swap Functions
In C, there are several ways to exchange the values of variables (swap them). Here we introduce three representative methods and discuss their advantages and disadvantages.
2.1 swap function using a temporary variable
The most common and intuitively easy-to-understand method is the use of a temporary (temp) variable. As shown below, the temporary variable temp is used to exchange values.
Code Example
#include <stdio.h>
// swap function (using pointers)
void swap(int *a, int *b) {
int temp = *a; // Save a's value in temporary variable
*a = *b; // Assign b's value to a
*b = temp; // Assign the temporary variable's value (original a) to b
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %dn", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %dn", x, y);
return 0;
}
Execution Result
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Explanation
temp temporarily stores the value of a
Assign the value of b to a
Assign the value of temp (original a) to b
Advantages & Disadvantages
Method
Advantages
Disadvantages
Use a temporary variable
High readability and less prone to bugs
Consumes memory for the temporary variable
Because this method is highly readable and safe, it is the most recommended approach for typical C programs.
2.2 swap function using XOR operation
By using the XOR (exclusive OR) operation, you can swap variable values without a temporary variable.
Code Example
#include <stdio.h>
// swap function using XOR
void swap(int *a, int *b) {
if (a != b) { // Prevent when the same address is passed
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %dn", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %dn", x, y);
return 0;
}
Execution Result
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Advantages & Disadvantages
Method
Advantages
Disadvantages
Use XOR operation
No temporary variable needed, low memory usage
Poor readability and prone to bugs
2.3 swap function using addition/subtraction
Similar to XOR, you can exchange variable values without a temporary variable by using addition and subtraction.
Code Example
#include <stdio.h>
// swap function using addition/subtraction
void swap(int *a, int *b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %dn", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %dn", x, y);
return 0;
}
Execution Result
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Advantages & Disadvantages
Method
Advantages
Disadvantages
Use addition/subtraction
No temporary variable needed, low memory usage
Risk of overflow
2.4 Comparison of swap methods
Technique
Advantages
Disadvantages
Applicable Scenarios
Use a temporary variable
High readability and safe
Consumes a little memory
General-purpose programs
Use XOR operation
Can save memory
Poor readability, prone to bugs
Embedded systems
Use addition/subtraction
Can save memory
Risk of overflow
Special cases (mathematical operation optimization)
Summary
Three implementation methods for swap functions in C were introduced.
In general, the “use a temporary variable” method is the safest and most readable, and is recommended.
Methods using XOR or addition/subtraction may be employed in embedded systems or special environments.
3. Using the swap function and pointers
The swap function introduced in the previous section used pointers throughout. This is closely related to how function arguments are handled in C. In this section, we will cover the basics of pointers while explaining in detail why the swap function requires pointers.
3.1 Difference between pass-by-value and pass-by-reference
In C functions, there is a characteristic that by default “pass-by-value” (call by value) is performed. In other words, a copy of the variable passed to the function is created, so changes inside the function do not affect the original variable.
Example of pass-by-value
#include <stdio.h>
// Pass-by-value swap function (incorrect method)
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %dn", x, y);
swap(x, y);
printf("After swap: x = %d, y = %dn", x, y);
return 0;
}
Output
Before swap: x = 5, y = 10
After swap: x = 5, y = 10 ← values were not swapped!
Explanation
When swap(x, y) is called, the function receives a copy of x and y.
Therefore, even if a and b are swapped inside the function, the original x and y remain unchanged.
To solve this problem, you need to use “pass-by-reference” (call by reference).
3.2 Swap function using pointers
By using pointers, you can pass the address of a variable to a function and modify its value directly.
Swap function using pointers
#include <stdio.h>
// Correct swap function (using pointers)
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %dn", x, y);
swap(&x, &y); // Pass address
printf("After swap: x = %d, y = %dn", x, y);
return 0;
}
Output
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Explanation
Pass the address of variables x and y, e.g., swap(&x, &y);.
In the swap function, you can directly modify the original variables’ values via the pointers a and b.
Thus, changes made inside the function are reflected in the main program.
3.3 Why are pointers needed in the swap function?
If you try to perform a swap without using pointers, the values will not be exchanged due to the nature of pass-by-value. By using pointers, you can manipulate the original variables directly, allowing the swap to work correctly.
Key points
Pass-by-value (swap(int a, int b)) passes a copy of the variable, so the result of the swap is not reflected in the original variables.
Using pointers (swap(int *a, int *b)) passes the address of the original variables, allowing direct modification.
3.4 Benefits of using pointers
Using pointers provides the following benefits beyond the swap function.
Pointer usage scenarios
Description
Modifying function arguments
When you want to change the value of a variable inside a function, as with the swap function.
Array manipulation
Since arrays are closely related to pointers, they can be manipulated efficiently.
Dynamic memory management
Memory management using malloc and free is possible.
Pointers are a crucial concept in C, and by understanding the swap function, you can learn the fundamentals of pointers.
Summary
In C, function arguments are passed by value by default, so if you don’t use pointers in a swap function, the values will not be exchanged.
Using pointers allows you to pass a variable’s address and modify its value directly.
Pointers can be used not only for swap functions but also for array manipulation, dynamic memory management, and more.
4. Applying swap functions to arrays and structs
In the previous section, we introduced a swap function for exchanging the values of basic variables. However, in C you can also apply the swap function to array elements and struct members. This section explains those applications in detail.
4.1 Swapping array elements
Swapping array elements enables you to perform sorting and specific data manipulations efficiently. You can use a pointer-based swap function to exchange array elements.
4.1.1 Swap function that swaps array elements
The code below implements a swap function that exchanges two specific elements of an array.
Code example
#include <stdio.h>
// swap function that swaps array elements
void swapArrayElements(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array before swap: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// swap array elements (swap index 0 and 4)
swapArrayElements(arr, 0, 4);
printf("Array after swap: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Execution result
Array before swap: 1 2 3 4 5
Array after swap: 5 2 3 4 1
Explanation
swapArrayElements(arr, 0, 4) swaps the 0th and 4th elements of the array arr.
Note: Specifying an index outside the bounds of arr results in undefined behavior (a common source of bugs), so use it carefully.
4.2 Swapping struct members
In C, you can use structs to group multiple data items of different types. It is also possible to swap instances of such structs.
4.2.1 Swap function that swaps struct values
The code below implements a function that swaps the entire struct instance (object).
Code example
#include <stdio.h>
#include <string.h>
// struct definition
typedef struct {
int id;
char name[20];
} Person;
// swap function for struct
void swapStruct(Person *p1, Person *p2) {
Person temp = *p1; // use temporary variable to swap
*p1 = *p2;
*p2 = temp;
}
int main() {
Person person1 = {1, "Alice"};
Person person2 = {2, "Bob"};
printf("Before swap:\n");
printf("Person 1: ID=%d, Name=%s\n", person1.id, person1.name);
printf("Person 2: ID=%d, Name=%s\n", person2.id, person2.name);
// swap struct values
swapStruct(&person1, &person2);
printf("After swap:\n");
printf("Person 1: ID=%d, Name=%s\n", person1.id, person1.name);
printf("Person 2: ID=%d, Name=%s\n", person2.id, person2.name);
return 0;
}
Execution result
Before swap:
Person 1: ID=1, Name=Alice
Person 2: ID=2, Name=Bob
After swap:
Person 1: ID=2, Name=Bob
Person 2: ID=1, Name=Alice
Summary
Swapping array elements enables data manipulation and sorting.
Swapping struct values makes managing rosters and data more efficient.
Swapping structs within an array helps organize large datasets.
5. Sorting Algorithms Using the swap Function
In the previous section, we explained how to swap elements of arrays and structs using the swap function. This swap function is also widely used in sorting algorithms. In this section, we introduce the representative sorting algorithms that utilize the swap function: Bubble Sort and Heap Sort.
5.1 Bubble Sort
5.1.1 What is Bubble Sort?
Bubble Sort is a simple algorithm that sorts an array by comparing adjacent elements and swapping them. It is the most basic sorting method, but because its time complexity is O(n²), it is unsuitable for sorting large datasets.
5.1.2 Implementation of Bubble Sort
Code Example
#include <stdio.h>
// swap function
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Bubble Sort function
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) { // sort in ascending order
swap(&arr[j], &arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
bubbleSort(arr, size);
printf("Array after sorting: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
return 0;
}
Output
Array before sorting: 5 2 9 1 5 6
Array after sorting: 1 2 5 5 6 9
5.2 Heap Sort
5.2.1 What is Heap Sort?
Heap Sort is a sorting algorithm that rearranges elements using a data structure called a heap. Its time complexity is O(n log n), making it efficient and suitable for sorting large amounts of data.
5.2.2 Implementation of Heap Sort
Code Example
#include <stdio.h>
// swap function
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to adjust the heap
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
// Heap Sort function
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
heapSort(arr, size);
printf("Array after sorting: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
return 0;
}
Output
Array before sorting: 5 2 9 1 5 6
Array after sorting: 1 2 5 5 6 9
Summary
The swap function is used as a fundamental component of sorting algorithms.
Bubble Sort is a simple algorithm, but it is not suitable for large datasets.
Heap Sort has a time complexity of O(n log n) and is used as a practical sorting method.
6. Summary
In this article, we provided a detailed explanation of how to implement and apply swap functions in C. Here, we review each section’s content and organize the importance of swap functions and the best ways to use them.
6.1 Review of This Article
In this article, we explained the following topics in detail.
Section
Summary
1. Introduction
Basic concepts of the swap function and the differences from C++’s std::swap
2. Basic Implementation of swap Function
Implementation of swap using temporary variables, XOR, and addition/subtraction
3. Using swap Function with Pointers
Why pointers are needed and the differences between pass-by-value and pass-by-reference
4. Swapping Arrays and Structures
Methods for swapping array elements and structure members and their applications
5. Sorting Algorithms Using swap Function
Implementation and comparison of bubble sort and heap sort
6.2 Best Practices for Using swap Function
To use the swap function effectively, keep the following points in mind.
Basic Variable Swapping
In typical programs, using a temporary variable is the safest method
In memory-constrained environments, using XOR or addition/subtraction can be effective (though readability suffers)
Swapping Elements of Arrays and Structures
Swap array elements using pointers and indices
When swapping structures, using pointers is efficient if members are large
Using swap in Sorting Algorithms
Bubble sort frequently uses the swap function
Swap is indispensable even in advanced algorithms like heap sort
6.3 Topics for Further Study
After mastering the swap function, we recommend studying the following topics to further improve your C programming skills.
Advanced Pointer Usage(arrays of pointers, function pointers)
Dynamic Memory Management(using malloc/free for data handling)