Generic Swap
Part of the Object Oriented Programming section of Coddy's C journey — lesson 51 of 61.
A common operation in programming is swapping two values. Normally, you'd write a separate swap function for each type — one for int, another for double, and so on. But with void* and memcpy, we can write a single function that swaps any two variables.
The key insight is that swapping is just moving bytes around. If you know the size of the data, you can copy bytes without knowing the actual type. The function signature looks like this:
void generic_swap(void* a, void* b, size_t size);The size parameter tells the function how many bytes to move. Inside, we use a temporary buffer and memcpy from <string.h> to shuffle the bytes:
void generic_swap(void* a, void* b, size_t size) {
char temp[size]; // temporary buffer
memcpy(temp, a, size); // temp = a
memcpy(a, b, size); // a = b
memcpy(b, temp, size); // b = temp
}Now this single function works for any type:
int x = 5, y = 10;
generic_swap(&x, &y, sizeof(int));
// x is now 10, y is now 5double p = 3.14, q = 2.71;
generic_swap(&p, &q, sizeof(double));
// p is now 2.71, q is now 3.14This pattern — using void* with size_t — is how C's standard library implements generic functions like qsort and bsearch.
Challenge
EasyLet's build a generic swap utility that can exchange the values of any two variables, regardless of their type — using the power of void* pointers and memcpy.
You'll organize your code across three files:
swap.h: Declare yourgeneric_swapfunction that takes twovoid*pointers and asize_tparameter indicating the size of the data to swap. Don't forget include guards!swap.c: Implement thegeneric_swapfunction. Use a temporary buffer andmemcpyto move bytes between the two memory locations. Remember the three-step swap pattern: copy first value to temp, copy second to first, copy temp to second.main.c: Demonstrate your generic swap working with different data types. Read a type indicator (ifor integers,dfor doubles) followed by two values. Create two variables of the appropriate type, swap them using yourgeneric_swapfunction, then print both values after the swap.
Your program will receive three inputs:
- A type indicator:
ifor integer ordfor double - The first value
- The second value
After swapping, print both values on separate lines. For doubles, use 2 decimal places.
Example output when the inputs are i, 5, and 10:
10
5Example output when the inputs are d, 3.14, and 2.71:
2.71
3.14Example output when the inputs are i, -7, and 42:
42
-7Example output when the inputs are d, 99.99, and 0.01:
0.01
99.99The beauty of this approach is that your generic_swap function has no idea what types it's swapping — it just moves bytes. The same function works for integers, doubles, structs, or any other data type. You'll need to include <string.h> for memcpy and <stddef.h> or <stdlib.h> for size_t.
Cheat sheet
A generic swap function uses void* pointers and memcpy to swap values of any type by moving bytes without knowing the actual type.
Function signature:
void generic_swap(void* a, void* b, size_t size);Implementation using a temporary buffer and memcpy:
void generic_swap(void* a, void* b, size_t size) {
char temp[size]; // temporary buffer
memcpy(temp, a, size); // temp = a
memcpy(a, b, size); // a = b
memcpy(b, temp, size); // b = temp
}Usage with different types:
int x = 5, y = 10;
generic_swap(&x, &y, sizeof(int));
// x is now 10, y is now 5
double p = 3.14, q = 2.71;
generic_swap(&p, &q, sizeof(double));
// p is now 2.71, q is now 3.14Required headers: <string.h> for memcpy and <stddef.h> or <stdlib.h> for size_t.
Try it yourself
#include <stdio.h>
#include "swap.h"
int main() {
char type;
scanf("%c", &type);
if (type == 'i') {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
// TODO: Call generic_swap to swap a and b
// Hint: Use &a, &b, and sizeof(int)
printf("%d\n", a);
printf("%d\n", b);
} else if (type == 'd') {
double a, b;
scanf("%lf", &a);
scanf("%lf", &b);
// TODO: Call generic_swap to swap a and b
// Hint: Use &a, &b, and sizeof(double)
printf("%.2f\n", a);
printf("%.2f\n", b);
}
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box7Function Pointers
Declaring Function PointersCalling Function PointersTypedef for Function PointersPassing Functions as ArgumentsRecap: Calculator Dispatch10Generic Containers
Void Pointers RecapGeneric WrapperGeneric SwapGeneric CompareRecap: Generic Array2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy