Advanced C Programming Cheat Sheet
Mastering C for Systems Programming
While C is a small language, mastering its nuances is essential for writing robust system-level code, OS kernels, and embedded firmware.
1. Pointers to Functions
Function pointers allow you to pass functions as arguments, enabling callbacks and state machines.
// Define a function pointer type
typedef int (*math_func)(int, int);
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int main() {
math_func op = add;
printf("Result: %d\n", op(5, 3)); // Prints 8
}
2. Struct Packing and Alignment
By default, compilers pad structs to align members to memory boundaries for performance. In embedded systems or networking, you often need to disable this.
// Use #pragma pack or __attribute__((packed))
struct __attribute__((packed)) NetworkHeader {
uint8_t version;
uint16_t length;
};
3. Bit Manipulation
Setting, clearing, and toggling bits is the bread and butter of embedded C.
#define BIT(x) (1 << (x)) uint32_t reg = 0; reg |= BIT(3); // Set bit 3 reg &= ~BIT(3); // Clear bit 3 reg ^= BIT(3); // Toggle bit 3
4. The 'volatile' Keyword
Tells the compiler that a variable's value can change at any time without any action being taken by the code nearby (e.g., hardware registers or variables modified inside an ISR). It prevents the compiler from optimizing away reads/writes.
Software