Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Preprocessor

Before the compiler reads a word of a program, the preprocessor rewrites its text. It replaces names with the text they stand for, keeps or drops whole blocks of lines, and reports problems of its own. Every line that starts with # is an instruction to it.

The simplest instruction is #define, which gives a name to a piece of text:

'' #define gives a name to a piece of text. The preprocessor puts the
'' text in place of every use of the name, before the program is
'' compiled.
#define APP_NAME "tally"
#define MAX_ITEMS 5
#define BANNER "-- " & APP_NAME & " --"

print BANNER
dim counts( 1 to MAX_ITEMS ) as int32
print "slots:"; ubound( counts )

'' #ifdef asks whether a name is defined; #undef removes it.
#undef MAX_ITEMS
#ifdef MAX_ITEMS
    print "MAX_ITEMS is defined"
#else
    print "MAX_ITEMS is not defined any more"
#endif

'' For a plain value, a const is usually the better choice: it has a
'' type and a scope, and the compiler checks it.
const LIMIT as int32 = 10
print "limit:"; LIMIT

Output

-- tally --
slots: 5
MAX_ITEMS is not defined any more
limit: 10
  • #define MAX_ITEMS 5 makes every later MAX_ITEMS read 5. The replacement is text, so BANNER becomes a whole expression, with APP_NAME replaced inside it.
  • #undef removes a definition, and #ifdef asks whether a name is defined at that point in the file. The conditional compilation page covers the full family.
  • const is the better tool for a plain value. A constant has a type and obeys scope, and a mistake in its value is reported where it is written, not at every use.

Use #define for what only the preprocessor can do: switches that choose which code is compiled, names for the build to set from outside, and macros that generate code.

Activities

  1. Change MAX_ITEMS to 8 and check the array follows.
  2. Use MAX_ITEMS after the #undef and read what the compiler says.