f78 Simple Macros Contents|Index|Previous|Next
 

Simple macros

A simple macro is a kind of abbreviation. It is a name which stands for a fragment of code. Some people refer to these as manifest constants. Before you can use a macro, you must define it explicitly with the #define directive. #define is followed by the name of the macro and then the code it should be an abbreviation for. For example, use the following. This input defines a macro named BUFFER_SIZE as an abbreviation for the text 1020. If somewhere after this #define directive there comes a C statement of the form of the following example, then the C preprocessor will recognize and expand the macro BUFFER_SIZE. This then gives the following result. The use of all uppercase for macro names is a standard convention so that it is possible to tell at a glance which names are macros.

Normally, a macro definition must be a single line, like all C preprocessing directives. (You can split a long macro definition cosmetically with Backslash-Newline.) There is one exception: newlines can be included in the macro definition if within a string or character constant. This is because it is not possible for a macro definition to contain an unbalanced quote character; the definition automatically extends to include the matching quote character that ends the string or character constant. Comments within a macro definition may contain newlines, which make no diff cc1 erence since the comments are entirely replaced with spaces regardless of their contents.

Aside from the previous explanation, there is no restriction on what can go in a macro body. Parentheses need not balance. The body need not resemble valid C code. (But if it does not, you may get error messages from the C compiler when you use the macro.)

The C preprocessor scans your program sequentially, so macro definitions take effect at the place you write them. First, input the following.

This produces the following output. After the preprocessor expands a macro name, the macro’s definition body is appended to the front of the remaining input, and the check for macro calls continues. Therefore, the macro body can contain calls to other macros. Use the following, for example, as input. Afterwards, name TABLESIZE when used in the program would go through two stages of expansion, resulting ultimately in 1020.

This is not at all the same as defining TABLESIZE to be 1020. The #define for TABLESIZE uses exactly the body you specify—in this case, BUFSIZE—and does not check to see whether it too is the name of a macro. It’s only when you use TABLESIZE that the result of its expansion is checked for more macro names. See Cascaded use of macros. 0