Mikroelektronika MIKROE-738 Datenbogen
258
mikoC PRO for PIC32
MikroElektronika
A macro won’t be expanded during its own expansion (so
#define MACRO MACRO
won’t expand indefinitely).
Here is an example:
/* Here are some simple macros: */
#define ERR_MSG “Out of range!”
#define EVERLOOP for( ; ; )
/* which we could use like this: */
main() {
EVERLOOP {
...
if (error) { Lcd_Out_Cp(ERR_MSG); break; }
...
}
}
Attempting to redefine an already defined macro identifier will result in a warning unless a new definition is exactly the
same token-by-token definition as the existing one. The preferred strategy when definitions might exist in other header
files is as follows:
#ifndef BLOCK_SIZE
#define BLOCK_SIZE 512
#endif
The middle line is bypassed if
BLOCK_SIZE
is currently defined; if
BLOCK_SIZE
is not currently defined, the middle
line is invoked to define it.
Macros with Parameters
The following syntax is used to define a macro with parameters:
#define macro_identifier(<arg_list>) <token_sequence>
Note that there can be no whitespace between
macro_identifier
and “(”. The optional
arg_list
is a sequence of
identifiers separated by commas, like the argument list of a C function. Each comma-delimited identifier has the role
of a formal argument or placeholder.
Such macros are called by writing
macro_identifier(<actual_arg_list>)
in the subsequent source code. The syntax is identical to that of a function call; indeed, many standard library C
“functions” are implemented as macros. However, there are some important semantic differences.
The optional
actual_arg_list
must contain the same number of comma-delimited token sequences, known as
actual arguments, as found in the formal arg_list of the
#define
line – there must be an actual argument for each formal
argument. An error will be reported if the number of arguments in two lists is not the same.