← The C Language Lesson 64 of 77 · 10 XP

Macros

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Lines that start with # are handled by the preprocessor — before the compiler. It works with text: it substitutes, cuts out, glues together.

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

Parentheses in macros are a must. Without them:

#define BAD_SQUARE(x) x * x
BAD_SQUARE(1 + 2)    // turns into 1 + 2 * 1 + 2 = 5, not 9

And even with parentheses, the argument is substituted as text, so SQUARE(i++) increases i twice.

Useful features:

#define STR(x) #x            // turn into a string: STR(abc) → "abc"
#define DEBUG 1

#if DEBUG
    fprintf(stderr, "x = %d\n", x);
#endif

#ifndef MY_HEADER_H          // an "include guard" in every .h file
#define MY_HEADER_H
...
#endif

Built-in macros: __FILE__, __LINE__, __func__ — handy in debug printing.

Advice: for constants, use const or enum; for functions, static inline. Leave macros for what only the preprocessor can do.

Task. Define the macros MAX(a, b) and ABS(x) (with the right parentheses!) and print, separated by spaces, MAX(a, b), ABS(a - b) and ABS(-a) * 2 for the a and b read.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.