Post

Chapter 11: The Preprocessor – Macros and Conditional Compilation

Explore the C preprocessor, macros, and conditional compilation.

Chapter 11: The Preprocessor – Macros and Conditional Compilation

Table of Contents

11.1 Macros

Macros are code shortcuts:

1
#define PI 3.14

11.2 Conditional Compilation

Use #ifdef, #ifndef, #endif to include/exclude code:

1
2
3
#ifdef DEBUG
    printf("Debug mode\n");
#endif

11.3 Exercises

  1. Define a macro for the square of a number.
  2. Use conditional compilation to print a message only if DEBUG is defined.
  3. What is the difference between #define and const?

11.4 Solutions

11.4.1 Solution 1

1
#define SQUARE(x) ((x)*(x))

11.4.2 Solution 2

1
2
3
#ifdef DEBUG
    printf("Debug!\n");
#endif

11.4.3 Solution 3

#define is handled by the preprocessor; const is handled by the compiler.

11.5 What’s Coming in the Next Chapter

Next, you’ll learn about bitwise operations in C!

Next Chapter → Bitwise Operations – Ones, Zeros, and Mind Tricks

This post is licensed under CC BY 4.0 by the author.