C Preprocessor & Macros

#define, #include and conditional compilation.

✍️ 2 exercises in this lesson

Lines starting with # are handled by the preprocessor before compilation:

  • #include: insert a header file.
  • #define PI 3.14159: a constant macro.
  • #define SQUARE(x) ((x) * (x)): a function-like macro (always wrap arguments in parentheses).
  • #ifdef / #ifndef / #endif: compile code only in certain conditions, e.g. debug builds.

Key Takeaways: C Preprocessor & Macros

Mastering C Preprocessor & Macros helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C Preprocessor & Macros Code Example

C
#include <stdio.h>

#define PI 3.14159
#define SQUARE(x) ((x) * (x))
#define DEBUG

int main() {
    double r = 2.0;
    printf("Area: %.2f\n", PI * SQUARE(r));

#ifdef DEBUG
    printf("[debug] radius = %.1f\n", r);
#endif
    return 0;
}
Output
Area: 12.57
[debug] radius = 2.0
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C Preprocessor & Macros Practice Exercises

Check what you learned in “C Preprocessor & Macros”.

/ 2 solved
Fill in the blank

Define a constant macro.

 PI 3.14159
✓ Correct! Not quite. Try again.
Multiple choice

Why wrap macro arguments in parentheses, as in ((x) * (x))?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services