Skip to content
C

Preprocessor Macros

Define object-like and function-like macros with conditional compilation.

By EZ4Code Team
preprocessormacro

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