Syntax:
#define macro-name replacement-string
The #define command is used to make substitutions throughout the file in which it is located. In other words, #define causes the compiler to go through the file, replacing every occurrence of macro-name with replacement-string. The replacement string stops at the end of the line.
Here's a typical use for a #define (at least in C):
#define TRUE 1 #define FALSE 0 ... int done = 0; while( done != TRUE ) { ... }
Another feature of the #define command is that it can take arguments, making it rather useful as a pseudo-function creator. Consider the following code:
#define absolute_value( x ) ( ((x) < 0) ? -(x) : (x) ) ... int num = -1; while( absolute_value( num ) ) { ... }
It's generally a good idea to use extra parentheses when using complex macros. Notice that in the above example, the variable “x” is always within it's own set of parentheses. This way, it will be evaluated in whole, before being compared to 0 or multiplied by -1. Also, the entire macro is surrounded by parentheses, to prevent it from being contaminated by other code. If you're not careful, you run the risk of having the compiler misinterpret your code. Here is an example of how to use the #define command to create a general purpose incrementing for loop that prints out the integers 1 through 20:
#define count_up( v, low, high ) \ for( (v) = (low); (v) <= (high); (v)++ ) ... int i; count_up( i, 1, 20 ) { printf( "i is %d\n", i ); }
Related topics: # and ##, #if,...,#endif, #undef