Chapter 10. C Preprocessor

The speech of man is like embroidered tapestries, since like them this has to be extended in order to display its patterns, but when it is rolled up it conceals and distorts them.

Themistocles

In the early days, when C was still being developed, it soon became apparent that C needed a facility for handling named constants, macros, and include files. The solution was to create a preprocessor that recognized these constructs in the programs before they were passed to the C compiler. The preprocessor is nothing more than a specialized text editor. Its syntax is completely different from that of C, and it has no understanding of C constructs.

The preprocessor was very useful, and soon it was merged into the main C compiler. On some systems, like UNIX, the preprocessor is still a separate program, automatically executed by the compiler wrapper cc. Some of the new compilers, like Turbo C++ and Microsoft Visual C++, have the preprocessor built in.

#define Statement

Example 10-1 initializes two arrays (data and twice). Each array contains 10 elements. Suppose we wanted to change the program to use 20 elements. Then we would have to change the array size (two places) and the index limit (one place). Aside from being a lot of work, multiple changes can lead to errors.

Example 10-1. init2a/init2a.c
int data[10]; /* some data */ int twice[10]; /* twice some data */ int main() { int index; /* index into the data */ for (index = 0; index < 10; ++index) { data[index] = index; ...

Get Practical C Programming, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.