Simple Text Replacement

Summary: The #define directive works like the search and replace function of a word processor.

At the simplest level, the #define directive works much like the “search and replace” function of a word processor, replacing one piece of text in the source file with another piece of text. The #define directive is commonly used to create a symbolic constant—a meaningful name for a “magic number” whose meaning might not otherwise be apparent. This improves the program's readability.

For instance, in the VOLUME.C program in Chapter 1, “Anatomy of a C Program,” the directive

#define PI 3.14

defines a symbolic constant named PI. The directive causes QuickC to replace every occurrence of the text PI in the VOLUME.C source program with the text 3.14. For example, when the compiler encounters the program line

result = 4 * PI * result;

it expands the line to read

result = 4 * 3.14 * result;

Besides making your program more readable, symbolic constants can streamline its maintenance. For instance, say you later decide to use 3.14159265 rather than 3.14 in VOLUME.C. All you need to change is one #define directive at the beginning of the program.

The replacement text can be longer than the 3.14159265 we used above. A replacement text can't be longer than 512 bytes in QuickC, but you'll rarely, if ever, have to worry about this limit.