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 5makes every laterMAX_ITEMSread5. The replacement is text, soBANNERbecomes a whole expression, withAPP_NAMEreplaced inside it.#undefremoves a definition, and#ifdefasks whether a name is defined at that point in the file. The conditional compilation page covers the full family.constis 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
- Change
MAX_ITEMSto8and check the array follows. - Use
MAX_ITEMSafter the#undefand read what the compiler says.