Preprocessor Macros
Define object-like and function-like macros with conditional compilation.
Code
#include <stdio.h>
// Object-like macro
#define PI 3.14159265358979
#define MAX_BUF 256
// Function-like macro
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// Conditional compilation
#ifdef DEBUG
#define LOG(msg) printf("[DEBUG] %s\n", msg)
#else
#define LOG(msg) ((void)0)
#endif
// Variadic macro
#define PRINT(fmt, ...) printf(fmt __VA_OPT__(,) __VA_ARGS__)
int main(void) {
double area = PI * SQUARE(5);
printf("area = %.2f\n", area);
printf("max = %d\n", MAX(3, 8));
LOG("running");
PRINT("count=%d name=%s\n", 7, "x");
return 0;
}Explanation
Macros are substituted by the preprocessor before compilation, so PI and SQUARE become literal text in the source. Always parenthesize macro parameters and bodies to avoid operator-precedence surprises. Conditional macros like LOG let debug output vanish from release builds with zero runtime cost.
More C Snippets
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
File I/O
Open, read, write, and close files using the stdio FILE API.
Structs
Group related fields with typedef and pass by pointer for mutation.
Function Pointers
Store function addresses for callbacks and dispatch tables.