CC Explainer
C · 1 · Foundations5 / 35 · 14%

The Preprocessor in Depth

Macros, include guards and conditional compilation — the code before the code.

Examples: #define, #ifdef, #pragma once

shortcuts: ← prev · → next · M mark
1

Object & Function Macros

Pure text substitution — no types, no scope, no safety net.

Syntax
syntax
#define MAX_USERS 100
#define MIN(a, b) ((a) < (b) ? (a) : (b))
WATCH OUT
MIN(i++, j) evaluates i++ twice. Prefer static inline functions when you can.
2

Include Guards

Stop a header being pasted twice into one translation unit.

Example
vec.h
#ifndef VEC_H
#define VEC_H

typedef struct { float x, y; } Vec;

#endif /* VEC_H */
#pragma once is shorter and supported everywhere in practice, but not standard C.
3

Conditional Compilation

Compile different code per platform, per build type.

Example
example
#ifdef DEBUG
  #define LOG(msg) fprintf(stderr, "[dbg] %s\n", msg)
#else
  #define LOG(msg) ((void)0)
#endif

#if defined(__linux__)
  #include <unistd.h>
#endif
4

Stringify & Token Paste

# turns an argument into a string, ## glues tokens together.

Example
example
#define STR(x)      #x
#define CONCAT(a,b) a##b

STR(hello)        // becomes "hello"
int CONCAT(my,Var) = 5;   // int myVar = 5;
Interview question
Why wrap a multi-statement macro in do { ... } while (0)?