SyntaxPilot
Courses/C Programming/Lesson 16
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C Programming · Lesson 16 of 30

Preprocessor and macros

queued

These are the notes for C episode 16. Every program you have written so far began with #include <stdio.h>. Today you find out what that line really does, and who reads it before the compiler starts: the preprocessor. It starts with a teacher's marks program that shows the wrong class average because the class size was written in four places; you fix it by inventing #define. Then you see what #include really does, write macros with arguments, fall into the two classic traps (missing brackets and x++), switch code on and off with #ifdef, meet __FILE__ and __LINE__, and learn include guards. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.

The problem: everyone got 70, the average says 58

A teacher's program was written for a class of 50, so the number 50 appeared in four places: the array size, two loops and the division. Ten new students join. The teacher changes 50 to 60 in three places and misses one:

#include <stdio.h>

int main() {
    int marks[60];                 // was 50
    for (int i = 0; i < 60; i++)   // was 50
        marks[i] = 70;             // everyone got 70

    int sum = 0;
    for (int i = 0; i < 50; i++)
        sum += marks[i];
    printf("Average: %d\n", sum / 60);   // was 50
    return 0;
}

Output:

Average: 58

Every student scored 70, so the average must be 70. The second loop still says 50: it adds only 50 students (3500) and then divides by 60. No error, no warning, just a wrong report.

Why it happened

  • The same number was written in four places.
  • Every time it changes, you must find every copy. Miss one and the copies silently disagree.
  • Idea: write the number once, give it a name, and use the name everywhere else.

#define: one name, one place

Real-life example: the wedding card printer.

At the print shop In C
The card design says [VENUE] in many places; the real hall name is written once on the order #define CLASS_SIZE 60: a name for a value
Before printing, a helper replaces every [VENUE] with the hall name The preprocessor replaces every CLASS_SIZE with 60
The printing press never sees [VENUE] The compiler only ever sees 60
#include <stdio.h>
#define CLASS_SIZE 60

int main() {
    int marks[CLASS_SIZE];
    for (int i = 0; i < CLASS_SIZE; i++)
        marks[i] = 70;

    int sum = 0;
    for (int i = 0; i < CLASS_SIZE; i++)
        sum += marks[i];
    printf("Average: %d\n", sum / CLASS_SIZE);
    return 0;
}

Output:

Average: 70

Next year the class has 75 students: change one line to #define CLASS_SIZE 75 and run again. Output is still Average: 70, because the array, both loops and the division all changed together.

Rules for #define:

  • Syntax: #define NAME replacement-text. No = and no ;.
  • By convention macro names are in CAPITALS, so you can tell them apart from variables.
  • A name defined this way is a macro. A plain name for a value is an object-like macro.

What the preprocessor does

main.c ──► preprocessor ──► compiler ──► main (the program)
 your code   handles every     sees plain C
             line starting #   code only
  • Every line that starts with # is a directive: an instruction for the preprocessor, not C code.
  • Before: int marks[CLASS_SIZE]; → after: int marks[75];. The compiler never knows CLASS_SIZE existed.
  • It is pure text replacement. It does no maths, knows no types and checks nothing. This one sentence explains every trap below.

Tip: on your own computer, gcc -E main.c prints the file after preprocessing, so you can see exactly what the compiler receives (the output starts with the hundreds of lines pasted in from stdio.h).

Trap 1: a semicolon at the end of #define

#include <stdio.h>
#define CLASS_SIZE 60;

int main() {
    int marks[CLASS_SIZE];
    return 0;
}

gcc says:

main.c: In function 'main':
main.c:2:22: error: expected ']' before ';' token
    2 | #define CLASS_SIZE 60;
      |                      ^
main.c:5:15: note: in expansion of macro 'CLASS_SIZE'
    5 |     int marks[CLASS_SIZE];
      |               ^~~~~~~~~~

The semicolon is part of the replacement text, so line 5 became int marks[60;];. Whenever an error says "in expansion of macro", look at the #define line, not the line that uses it.

What #include really does

Real-life example: "for the masala, see page 12".

In a recipe book In C
"For the masala, see page 12" #include <stdio.h> points to another file
Photocopy page 12 and staple it in right there The preprocessor pastes the whole file's text in place of the line
Page 12 lists what goes into the masala stdio.h declares printf, scanf and friends: it tells the compiler they exist and how to call them

Remove the include and see what happens:

int main() {
    printf("Hello\n");
    return 0;
}

gcc says (and the program still prints Hello):

main.c: In function 'main':
main.c:2:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    2 |     printf("Hello\n");
      |     ^~~~~~
main.c:1:1: note: include '<stdio.h>' or provide a declaration of 'printf'
  +++ |+#include <stdio.h>
    1 | int main() {
main.c:2:5: warning: incompatible implicit declaration of built-in function 'printf' [-Wbuiltin-declaration-mismatch]
    2 |     printf("Hello\n");
      |     ^~~~~~
main.c:2:5: note: include '<stdio.h>' or provide a declaration of 'printf'

The compiler had never heard of printf, so it guessed. Never rely on the guess (newer compilers and the C23 standard make it an error). With #include <stdio.h> back at the top, the program compiles with no warnings and prints Hello.

Form Meaning Example
#include <file.h> A system header that comes with the compiler <stdio.h>, <string.h>, <stdlib.h>
#include "file.h" Your own header, looked for in your project folder first "marks.h" (episode 20)

Macros with arguments

A macro can take arguments, like a function. This is a function-like macro:

#define SQUARE(x) x * x

SQUARE(5) becomes the text 5 * 5: the argument's text replaces x. There is no space allowed between the macro name and ( in the definition.

Trap 2: missing brackets

#include <stdio.h>
#define SQUARE(x) x * x

int main() {
    printf("SQUARE(5)   = %d\n", SQUARE(5));
    printf("SQUARE(2+3) = %d\n", SQUARE(2 + 3));
    return 0;
}

Output:

SQUARE(5)   = 25
SQUARE(2+3) = 11

Do the replacement by hand: SQUARE(2 + 3) → 2 + 3 * 2 + 3. Multiplication goes first: 2 + 6 + 3 = 11. The preprocessor did not add brackets, because it doesn't do maths.

First fix: brackets around every argument.

#include <stdio.h>
#define SQUARE(x) (x) * (x)

int main() {
    printf("SQUARE(5)   = %d\n", SQUARE(5));
    printf("SQUARE(2+3) = %d\n", SQUARE(2 + 3));
    printf("100 / SQUARE(5) = %d\n", 100 / SQUARE(5));
    return 0;
}

Output:

SQUARE(5)   = 25
SQUARE(2+3) = 25
100 / SQUARE(5) = 100

Still wrong for the last one: 100 / (5) * (5) divides first (20), then multiplies (100).

Full fix: brackets around every argument AND around the whole body.

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

Same main, output:

SQUARE(5)   = 25
SQUARE(2+3) = 25
100 / SQUARE(5) = 4

Rule: in a function-like macro, put brackets around every use of every argument and around the whole body.

Trap 3: x++ is pasted twice

Brackets can't fix this one.

#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int max_fn(int a, int b) { return a > b ? a : b; }

int main() {
    int x = 5, y = 3;
    int m = MAX(x++, y);
    printf("macro:    m = %d, x = %d\n", m, x);

    x = 5;
    m = max_fn(x++, y);
    printf("function: m = %d, x = %d\n", m, x);
    return 0;
}

Output:

macro:    m = 6, x = 7
function: m = 5, x = 6

The macro becomes ((x++) > (y) ? (x++) : (y)). The text x++ appears twice, so it runs twice: the comparison sees 5 (then x is 6), and the answer is the second x++, which gives 6 (then x is 7). A function receives the value once, so it behaves as expected.

Rules: never pass anything with a side effect (x++, --n, a function call that prints or changes something) to a macro. For real calculations a normal function is usually the safer choice; keep macros for names and small, simple shortcuts.

Macro vs function

Macro Function
When it happens Text pasted before compiling Called while the program runs
Type checking None Arguments are checked and converted
Arguments Text, may be evaluated many times Evaluated exactly once
Brackets trap Yes No
Works for any type Yes (SQUARE works for int and double) One function per type (in C)
Debugging Harder (errors say "in expansion of macro") Easy

#ifdef: switching code on and off

Real-life example: the teacher's edition and the student's edition. Both are printed from one master copy; one has the answers in the margin, the other doesn't. You don't keep two books up to date.

A textbook In C
Teacher's edition: answers kept #define DEBUG: the debug lines are kept
Student's edition: same book, no answers // #define DEBUG: the debug lines are removed
One master copy #ifdef ... #endif: one source file, two programs
#include <stdio.h>
#define DEBUG

int main() {
    int stock = 20, sold = 25;
#ifdef DEBUG
    printf("[debug] stock=%d sold=%d\n", stock, sold);
#endif
    printf("Left: %d\n", stock - sold);
    return 0;
}

Output:

[debug] stock=20 sold=25
Left: -5

#define DEBUG has no value at all: it just defines the name. Comment it out (// #define DEBUG) and run again:

Left: -5

The debug line is gone, without deleting it. This is conditional compilation: the removed lines are never compiled, so they are not even in the program. (On your own computer you can also switch it from the command line with gcc -DDEBUG main.c.)

The conditional directives

Directive Keeps the lines below it when...
#ifdef NAME NAME is defined
#ifndef NAME NAME is not defined
#if expression the constant expression is true (non-zero), e.g. #if LEVEL >= 2
#elif expression the earlier tests failed and this one is true
#else none of the tests above were true
#endif ends the block (every #if... needs one)

#if with values (verified):

#include <stdio.h>
#define LEVEL 2

int main() {
#if LEVEL >= 2
    printf("Detailed log\n");
#else
    printf("Short log\n");
#endif
    return 0;
}

Output:

Detailed log

Also useful: #undef NAME removes a macro, and defined(NAME) can be used inside #if (#if defined(DEBUG) && LEVEL > 1).

Ready-made macros: __FILE__, __LINE__, __DATE__, __TIME__

#include <stdio.h>

int main() {
    printf("File:  %s\n", __FILE__);
    printf("Line:  %d\n", __LINE__);
    printf("Line:  %d\n", __LINE__);
    printf("Built: %s at %s\n", __DATE__, __TIME__);
    return 0;
}

Output (the date and time are when you compile it):

File:  main.c
Line:  5
Line:  6
Built: Oct 29 2026 at 07:28:43
Macro Value
__FILE__ The source file's name, as a string
__LINE__ The line number where it is written, as an int
__DATE__ The compile date, like "Oct 29 2026"
__TIME__ The compile time, like "07:28:43"

Include guards

Big programs split code into header files (episode 20). If marks.h gets included twice (directly, or through another header), its whole text is pasted twice, and something like a struct defined twice gives error: redefinition of 'struct ...'. Every header protects itself with an include guard:

#ifndef MARKS_H
#define MARKS_H

/* ... the header's contents ... */

#endif
  • First time: MARKS_H isn't defined, so the contents are kept and MARKS_H gets defined.
  • Second time: MARKS_H is already defined, so everything up to #endif is skipped.

Many compilers also accept the shorter #pragma once at the top of a header; it is very common but not part of the C standard, so the #ifndef form is the portable one.

Common mistakes (and the real gcc messages)

Mistake What you see Why Fix
#define CLASS_SIZE 60; error: expected ']' before ';' token + note: in expansion of macro 'CLASS_SIZE' The ; is pasted too #define CLASS_SIZE 60
#define SQUARE(x) x * x No error: SQUARE(2 + 3) is 11 Text, not maths ((x) * (x))
#define SQUARE(x) (x) * (x) No error: 100 / SQUARE(5) is 100 No brackets around the body ((x) * (x))
MAX(x++, y) No error: x goes up twice x++ is pasted twice A function, or no ++ inside
printf with no #include <stdio.h> warning: implicit declaration of function 'printf' printf was never declared #include <stdio.h>
#define SIZE = 10 Errors where SIZE is used (e.g. int a[SIZE]; → expected expression before '=' token) The = is pasted too #define SIZE 10
#ifdef DEBUG with no #endif error: unterminated #ifdef Every #if... needs an #endif Add #endif
A header included twice, no guard error: redefinition of ... Its text was pasted twice Include guard

Mini project: a bill with a debug SHOW macro

A shop bill with one debug switch. SHOW(x) prints the line number, the name of the variable and its value; with DEBUG off it becomes nothing.

#include <stdio.h>
#define DEBUG
#define GST_RATE 18
#define ITEMS 3

#ifdef DEBUG
#define SHOW(x) printf("[line %d] %s = %d\n", __LINE__, #x, x)
#else
#define SHOW(x)
#endif

int main() {
    int price[ITEMS] = {100, 250, 650};
    int subtotal = 0;
    for (int i = 0; i < ITEMS; i++)
        subtotal += price[i];
    SHOW(subtotal);
    int gst = subtotal * GST_RATE / 100;
    SHOW(gst);
    printf("Total: Rs %d\n", subtotal + gst);
    return 0;
}

Output:

[line 17] subtotal = 1000
[line 19] gst = 180
Total: Rs 1180

With // #define DEBUG:

Total: Rs 1180

New tool: #x, the stringizing operator. A single # before a macro argument turns it into a string literal of its text: SHOW(gst) gives "gst". __LINE__ inside the macro is the line where SHOW is used, because the macro is pasted there before __LINE__ is replaced. When DEBUG is off, SHOW(subtotal); becomes just ;, an empty statement, which is harmless.

Try it: add a fourth item by changing ITEMS to 4 and adding a price.

Practice

  1. #define PI 3.14159 and print the area of a circle of radius 7.
  2. Write CUBE(x) with all the brackets; test CUBE(3) and CUBE(1 + 2) (both should be 27).
  3. With #define LANG_HINDI, print "Namaste" using #ifdef / #else, otherwise "Hello".
  4. Write SHOWF(x) that prints a double with two decimals, and use it.
Solutions

All four in one program (verified):

#include <stdio.h>
#define PI 3.14159
#define CUBE(x) ((x) * (x) * (x))
#define LANG_HINDI
#define SHOWF(x) printf("[line %d] %s = %.2f\n", __LINE__, #x, x)

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

    printf("CUBE(3) = %d, CUBE(1 + 2) = %d\n", CUBE(3), CUBE(1 + 2));

#ifdef LANG_HINDI
    printf("Namaste\n");
#else
    printf("Hello\n");
#endif

    SHOWF(area);
    return 0;
}

Output:

Area: 153.94
CUBE(3) = 27, CUBE(1 + 2) = 27
Namaste
[line 20] area = 153.94

Without the brackets, CUBE(1 + 2) would be 1 + 2 * 1 + 2 * 1 + 2 = 7.

Quick quiz

What does this print?

#define DOUBLE(x) x + x
printf("%d", 3 * DOUBLE(4));
  • A. 24
  • B. 16
  • C. 28
  • D. 12
Answer

B: 16. The text becomes 3 * 4 + 4. Multiply first: 12, plus 4 is 16. With #define DOUBLE(x) ((x) + (x)) it would print 24. (Verified output: 16.)

Interview questions

  • What is the preprocessor? When does it run, compared to the compiler?
  • What does #include do? What is the difference between <file.h> and "file.h"?
  • What is the difference between #define PI 3.14 and const double PI = 3.14;? (A macro is text with no type and no memory; a const variable has a type, an address and is checked by the compiler.)
  • Why does #define SQUARE(x) x * x give the wrong answer for SQUARE(2 + 3)? How do you fix it?
  • What goes wrong with MAX(i++, j)? Why doesn't a function have this problem?
  • Macro vs function: list the advantages and disadvantages.
  • What is conditional compilation? Give a real use (debug logs, different operating systems, feature switches).
  • What is an include guard and why is it needed? What is #pragma once?
  • What are __FILE__ and __LINE__ used for?
  • What does the # operator do inside a macro? (And ##, which joins two tokens: #define JOIN(a, b) a##b.)
  • How can you see the output of the preprocessor? (gcc -E main.c)

Glossary

Term Meaning Example
Preprocessor The step that reads your file before the compiler and handles every # line Replaces CLASS_SIZE with 60
Directive A line starting with #: an instruction for the preprocessor, not C code #define, #include, #ifdef
Macro A name that the preprocessor replaces with some text CLASS_SIZE
Object-like macro A macro with no arguments: a name for a value #define CLASS_SIZE 60
Function-like macro A macro that takes arguments #define SQUARE(x) ((x) * (x))
Expansion Replacing a macro with its text SQUARE(5) → ((5) * (5))
Replacement text Everything after the name in a #define, up to the end of the line 60 in #define CLASS_SIZE 60
Header file A .h file of declarations meant to be included stdio.h
Declaration A line telling the compiler that something exists and how to use it printf is declared in stdio.h
Implicit declaration The compiler guessing about a function it was never told about (a warning; an error in newer C) printf without stdio.h
System header A header that comes with the compiler, included with < > <stdio.h>
Side effect Something an expression changes besides giving a value x++ changes x
Conditional compilation Keeping or removing lines before compiling, based on macros #ifdef DEBUG ... #endif
#ifdef / #ifndef Keep the lines if a name is / is not defined #ifdef DEBUG
#if / #elif / #else / #endif Keep lines based on a constant test; #endif ends the block #if LEVEL >= 2
#undef Removes a macro definition #undef DEBUG
Predefined macro A macro the compiler gives you ready-made __FILE__, __LINE__, __DATE__, __TIME__
Stringizing operator # Turns a macro argument into a string of its text #x → "gst"
Include guard #ifndef X_H / #define X_H / #endif around a header, so it is pasted only once MARKS_H
#pragma once A common (non-standard) one-line include guard Top of a header
Translation unit One .c file after the preprocessor has pasted in all its includes: what the compiler actually compiles main.c + stdio.h's text

Summary

  • A number written in many places drifts apart; #define NAME value gives it one name and one place to change.
  • The preprocessor runs before the compiler and handles every # line. It does pure text replacement.
  • #define lines have no = and no ;; errors that say "in expansion of macro" point back to the #define.
  • #include pastes a whole file in; headers declare functions like printf.
  • Function-like macros need brackets around every argument and around the whole body: ((x) * (x)).
  • Never pass x++ (or anything with a side effect) to a macro; it may run more than once. Prefer a function for real work.
  • #ifdef / #if / #else / #endif switch code on and off; removed lines are never compiled.
  • __FILE__ and __LINE__ tell you where you are; #x turns an argument into a string.
  • Include guards stop a header from being pasted twice.

Next episode: Storage classes: auto, static, extern and register, how long a variable lives and who can see it.