Course contentsShow
← C
Lesson 511 of 1,2197. PointersFree lesson

Generic functions in C

Generic functions in C

What you'll learn: How to use void pointers to create flexible functions that can handle any data type.

Imagine you are designing a high-tech shipping crate. If you build a crate specifically shaped for a bicycle, you can’t use it to ship a refrigerator. In programming, a function that only accepts int is like that bicycle crate—it’s rigid. A generic function is like a universal shipping container; it doesn't care what is inside as long as it follows basic handling instructions.

The "Universal Connector"

In C, the void * (void pointer) is the key to generic logic. It is a "blind" pointer. It holds a memory address, but the compiler has no idea what is stored at that address. Because a void * can point to an int, a float, or even a custom struct, we can pass any data type into a single function.

However, there is a catch: since the function is "blind," it doesn't know how big the data is. To solve this, we usually pass the size of the data as a second argument.

Seeing it in Action: A Generic Swapper

Normally, to swap two numbers, you’d need different functions for int and double. With generic logic and the memcpy function (which copies raw bytes), we can write one function for everything.

#include <stdio.h>
#include <string.h>

// A generic swap function
void generic_swap(void *a, void *b, size_t size) {
    // Create a temporary buffer to hold the bytes
    char temp[size]; 
    
    // Copy bytes from a to temp, b to a, and temp to b
    memcpy(temp, a, size);
    memcpy(a, b, size);
    memcpy(b, temp, size);
}

int main() {
    int x = 10, y = 20;
    double p = 3.14, q = 2.71;

    // We must tell the function how many bytes to swap
    generic_swap(&x, &y, sizeof(int));
    generic_swap(&p, &q, sizeof(double));

    printf("Swapped ints: %d, %d\n", x, y);
    printf("Swapped doubles: %.2f, %.2f\n", p, q);
    return 0;
}

How it Works

When we call generic_swap, we cast our specific data addresses into void *. Inside the function, we treat the data as a raw sequence of bytes. By using char temp[size], we create a workspace just big enough for the data, regardless of whether it’s a tiny character or a massive structure. This allows you to write tools—like sorting algorithms or linked lists—that work for every data type you will ever invent.

Key takeaway

Generic functions use void * to accept any data type and size_t to understand how much memory to process.