ZetCode

The C preprocessor in K&R C

last modified December 5, 2026 K&R C 1978

Before a C program is compiled, it passes through the preprocessor. The preprocessor works on the text of the program: it reads lines that start with #, includes other files, replaces names with their definitions, and drops parts of the program depending on conditions. The compiler proper never sees these lines. This article covers the preprocessor of the book: #include, #define with and without arguments, #undef, and the conditional lines #if, #ifdef, #ifndef, #else, and #endif.

File inclusion

A line #include "file" is replaced by the contents of the file. A name in double quotes is looked for first in the directory of the source file; a name in angle brackets, as in <stdio.h>, only in the system directory, /usr/include on UNIX.

defs.h
/* defs.h: definitions shared by several programs */
#define YES     1
#define NO      0
#define MAXWORD 20

defs.h holds symbolic constants that several programs share. It contains no code, only definitions.

incl.c
#include <stdio.h>
#include "defs.h"

int isvowel(c)
int c;
{
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        return YES;
    return NO;
}

int main()
{
    char *s;
    int n;

    n = 0;
    for (s = "preprocessor"; *s != '\0'; s++)
        if (isvowel(*s) == YES)
            n++;
    printf("%d vowels, words up to %d characters\n", n, MAXWORD - 1);
    return 0;
}

After the inclusion, YES, NO, and MAXWORD are defined in incl.c as if they had been written there. When a definition in the header changes, every file that includes it must be compiled again. The program structure article uses header files to share declarations between the files of a program.

$ gcc -std=c89 -pedantic -Wall -Wextra -o incl incl.c
$ ./incl
4 vowels, words up to 19 characters

Macro substitution

A line #define name text defines a macro: from then on, the name is replaced by the text wherever it occurs as a separate word, but not inside strings. The replacement text is the rest of the line and can be anything, not just a number. #undef removes a definition, so the name can be defined again.

subst.c
#define MAXVAL  100
#define forever for (;;)
#define begin   {
#define end     }

int limit = MAXVAL;

int loop()
begin
    int n;

    n = 0;
    forever begin
        if (++n >= limit)
            break;
    end
    return n;
end

#undef MAXVAL
#define MAXVAL  200

int other = MAXVAL;

forever stands for an infinite loop, and begin and end make C look like Algol; the source of the Bourne shell was written with such macros. The second definition of MAXVAL follows an #undef, so the two variables get different values. The -E option runs only the preprocessor and prints the result; -P leaves out the line markers it would add for the compiler.

$ gcc -E -P subst.c
int limit = 100;
int loop()
{
    int n;
    n = 0;
    for (;;) {
        if (++n >= limit)
            break;
    }
    return n;
}
int other = 200;

Macros with arguments

A macro can have parameters. The parenthesis after the name must follow it without a space; at each use, the arguments replace the parameters in the replacement text. The substitution is purely textual, which makes parentheses important.

macargs.c
#include <stdio.h>

#define square(x)   x * x
#define SQUARE(x)   ((x) * (x))
#define max(a, b)   ((a) > (b) ? (a) : (b))

int main()
{
    int i;

    i = 3;
    printf("square(i + 1) = %d\n", square(i + 1));
    printf("SQUARE(i + 1) = %d\n", SQUARE(i + 1));
    printf("100 / square(2) = %d\n", 100 / square(2));
    printf("100 / SQUARE(2) = %d\n", 100 / SQUARE(2));
    printf("max(i, 7) = %d\n", max(i, 7));
    printf("max(2.5, 1.5) = %f\n", max(2.5, 1.5));
    return 0;
}

square(i + 1) becomes i + 1 * i + 1, which is 7, not 16. SQUARE puts parentheses around each parameter and around the whole text, so its arguments and its result stay together: 100 / square(2) is 100 / 2 * 2. A macro does not care about types: max works for integers and for floating-point numbers alike, which a function in K&R C cannot do.

$ gcc -std=c89 -pedantic -Wall -Wextra -o macargs macargs.c
$ ./macargs
square(i + 1) = 7
SQUARE(i + 1) = 16
100 / square(2) = 100
100 / SQUARE(2) = 25
max(i, 7) = 7
max(2.5, 1.5) = 2.500000

Arguments evaluated twice

A macro parameter that appears twice in the replacement text puts its argument into the expansion twice, and the argument is evaluated each time. This matters when the argument has a side effect.

sideeff.c
#include <stdio.h>

#define max(a, b)   ((a) > (b) ? (a) : (b))

int count;

int next()
{
    return ++count;
}

int main()
{
    int i, j, k;

    i = 3;
    j = 5;
    k = max(i++, j++);
    printf("k = %d, i = %d, j = %d\n", k, i, j);

    k = max(next(), 0);
    printf("k = %d, count = %d\n", k, count);
    return 0;
}

max(i++, j++) expands to ((i++) > (j++) ? (i++) : (j++)). Both variables are incremented in the comparison, and the larger one, j, is incremented again when it is chosen. k gets 6, the value of j after the first increment, and j ends at 7. max(next(), 0) calls the function twice. A function call evaluates each argument once, so arguments with side effects belong in functions, not in macros.

$ gcc -std=c89 -pedantic -Wall -Wextra -o sideeff sideeff.c
$ ./sideeff
k = 6, i = 4, j = 7
k = 2, count = 2

Parameters inside strings

A macro that prints an expression would be more useful if it could print the expression itself too. This program writes the parameter x inside the string of show, and the parameter c inside a character constant.

strsub.c
#include <stdio.h>

#define show(x)     printf("x = %d\n", x)
#define letter(c)   'c'

int main()
{
    int count, total;

    count = 5;
    total = 12;
    show(count);
    show(total);
    show(count * total);
    printf("%c\n", letter(z));
    return 0;
}

GCC does not replace anything inside strings and character constants, so every line says x and the letter is c.

$ gcc -std=c89 -pedantic -Wall -Wextra -o strsub strsub.c
$ ./strsub
x = 5
x = 12
x = 60
c

The preprocessor of V7 UNIX replaces macro parameters inside strings and character constants as well, so show prints the expression it was given and letter(z) becomes 'z'. Programs of the time used this for debugging macros. Later C replaced the trick with the # operator, which the porting article shows.

$ cc strsub.c
$ a.out
count = 5
total = 12
count * total = 60
z

Conditional compilation

Conditional lines include or drop parts of the program. #ifdef name keeps the following lines if the name is defined, and #ifndef name if it is not. #if tests a constant expression, which may use macros. Each condition ends with #endif and can have an #else part. The -D option of the compiler defines a name from the command line, so one source file can be compiled in several ways.

debug.c
#include <stdio.h>

#ifndef LEVEL
#define LEVEL 1
#endif

#ifdef DEBUG
#define TRACE(s)    printf("trace: %s\n", s)
#else
#define TRACE(s)
#endif

int main()
{
    int i, sum;

    TRACE("start");
    sum = 0;
    for (i = 1; i <= 10; i++)
        sum += i;
#if LEVEL > 1
    printf("level %d\n", LEVEL);
#endif
    printf("sum %d\n", sum);
    TRACE("end");
    return 0;
}

LEVEL gets the value 1 unless it is already defined. With DEBUG defined, TRACE prints its argument; without it, the macro expands to nothing, and TRACE("start"); leaves an empty statement. -DDEBUG defines DEBUG as 1, and -DLEVEL=2 gives LEVEL the value 2.

$ gcc -std=c89 -pedantic -Wall -Wextra -o debug debug.c
$ ./debug
sum 55
$ gcc -std=c89 -pedantic -Wall -Wextra -DDEBUG -DLEVEL=2 -o debug debug.c
$ ./debug
trace: start
level 2
sum 55
trace: end

Machine names

The compiler of V7 UNIX defines two names before it reads the program: unix and pdp11. Programs test them to choose code for the system and the machine they are compiled on.

machine.c
#include <stdio.h>

int main()
{
#ifdef unix
    printf("unix is defined\n");
#else
    printf("unix is not defined\n");
#endif

#ifdef pdp11
    printf("pdp11 is defined\n");
#else
    printf("pdp11 is not defined\n");
#endif

    printf("an int has %d bits\n", (int) sizeof(int) * 8);
    return 0;
}

GCC with -std=c89 does not define unix, since a program may use that name for its own purposes; it defines __unix__ and __x86_64__ instead, with underscores that keep them out of the way of ordinary names.

$ gcc -std=c89 -pedantic -Wall -Wextra -o machine machine.c
$ ./machine
unix is not defined
pdp11 is not defined
an int has 32 bits

On the PDP-11, both names are defined and an int has 16 bits.

$ cc machine.c
$ a.out
unix is defined
pdp11 is defined
an int has 16 bits

Include guards

A header can be included twice, for example directly and through another header. Included twice, the declaration of a structure appears twice, which is an error. An include guard wraps the whole header in #ifndef, so its contents are read only once.

point.h
#ifndef POINT_H
#define POINT_H

struct point {
    int x;
    int y;
};

#endif

The first time point.h is read, POINT_H is not defined, so the lines up to #endif are kept and POINT_H gets defined. Any later inclusion finds the name defined and skips the whole file.

rect.h
#ifndef RECT_H
#define RECT_H

#include "point.h"

struct rect {
    struct point pt1;
    struct point pt2;
};

#endif

rect.h needs struct point, so it includes point.h itself, and it has a guard of its own.

guards.c
#include <stdio.h>
#include "point.h"
#include "rect.h"

int main()
{
    struct point p;
    struct rect r;

    p.x = 3;
    p.y = 4;
    r.pt1.x = r.pt1.y = 0;
    r.pt2.x = 10;
    r.pt2.y = 5;
    printf("p = (%d, %d), area of r = %d\n", p.x, p.y,
        (r.pt2.x - r.pt1.x) * (r.pt2.y - r.pt1.y));
    return 0;
}

guards.c includes both headers, so point.h is read twice. The second time, the guard skips it. Without the guards, GCC would stop with redefinition of 'struct point'.

$ gcc -std=c89 -pedantic -Wall -Wextra -o guards guards.c
$ ./guards
p = (3, 4), area of r = 50

Choosing among several cases

The conditional lines of the book have no form for a chain of tests. A choice among several cases is written with an #if nested in the #else part of another, each with its own #endif.

levels.c
#include <stdio.h>

#ifndef LEVEL
#define LEVEL 2
#endif

#if LEVEL == 0
#define MESSAGE "silent"
#else
#if LEVEL == 1
#define MESSAGE "normal"
#else
#define MESSAGE "verbose"
#endif
#endif

int main()
{
    printf("level %d: %s\n", LEVEL, MESSAGE);
    return 0;
}

LEVEL is 2, so the first test fails, the second fails too, and the inner #else defines MESSAGE as "verbose". The two #endif lines close the two #if lines.

$ gcc -std=c89 -pedantic -Wall -Wextra -o levels levels.c
$ ./levels
level 2: verbose

The #elif line

GCC also accepts #elif, which combines an #else with an #if and needs no extra #endif.

elif.c
#include <stdio.h>

#ifndef LEVEL
#define LEVEL 2
#endif

#if LEVEL == 0
#define MESSAGE "silent"
#elif LEVEL == 1
#define MESSAGE "normal"
#else
#define MESSAGE "verbose"
#endif

int main()
{
    printf("level %d: %s\n", LEVEL, MESSAGE);
    return 0;
}

The program is shorter, and GCC builds it with the same result.

$ gcc -std=c89 -pedantic -Wall -Wextra -o elif elif.c
$ ./elif
level 2: verbose

The V7 preprocessor does not know #elif and stops with undefined control. It rejects #error the same way. A program for the compilers of the time uses the nested form of the previous section.

$ cc elif.c
elif.c: 9: undefined control

Source

Dennis Ritchie: C Reference Manual (1975)

The GNU C Preprocessor: Traditional Mode

In this article we have used the preprocessor of K&R C: file inclusion, macro substitution and #undef, macros with arguments, arguments evaluated twice, parameters replaced inside strings on the PDP-11, conditional compilation with -D, the predefined unix and pdp11, include guards, and nested conditions in place of #elif. The next part of the series covers formatted output.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.