Generics
Goal: To write C code that operates on any data type, reducing code duplication and improving reusability. Generic functions in C are used for various purposes like sorting, searching, and memory management.
The Need for Generic Swap
The lecture uses the example of a swap function to illustrate the need for generics.
Initially, type-specific swap functions are created (swap_int, swap_short, swap_string).
This leads to code duplication, as the logic for swapping is the same regardless of the data type.
void swap_int(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void swap_short(short *a, short *b) {
short temp = *a;
*a = *b;
*b = temp;
}
void swap_string(char **a, char **b) {
char *temp = *a;
*a = *b;
*b = temp;
}
Generic Swap Implementation
The solution is to use void * to create a generic swap function.
void * is a pointer to an unknown data type, allowing the function to accept pointers to any type.
The generic swap function takes the addresses of the data to be swapped and the size of the data in bytes as arguments.
void swap(void *data1ptr, void *data2ptr, size_t nbytes) {
char temp[nbytes];
memcpy(temp, data1ptr, nbytes);
memcpy(data1ptr, data2ptr, nbytes);
memcpy(data2ptr, temp, nbytes);
}
temp[nbytes] creates a temporary buffer to hold the data.
memcpy is used to copy the data between the addresses and the temporary buffer because we can’t dereference a void * directly.
memcpy and memmove
memcpy: Copies n bytes from src to dest. It assumes no overlap between the source and destination regions.
void *memcpy(void *dest, const void *src, size_t n);
int x = 5;
int y = 4;
memcpy(&x, &y, sizeof(x)); // x becomes 4
memmove: Similar to memcpy but handles overlapping regions correctly.
void *memmove(void *dest, const void *src, size_t n);
Generics Pitfalls
Type Casting: void * needs to be cast to a specific type before dereferencing
Swap Ends
void swap_ends(void *arr, size_t nelems, size_t elem_bytes) {
swap(arr, (char *)arr + (nelems– 1) * elem_bytes, elem_bytes);
}
You’re asked to write a function that swaps the first and last elements in an array of numbers. Well, now it can swap for an array of anything!