#define is used to perform macro substitutions of one piece of text for another. The general form of the directive is

#define macro-name character-sequence

Here, each time macro-name is encountered, the specified character-sequence is substituted. Notice that there is no semicolon in this statement. Further, once the character sequence has started, it is terminated only by the end of the line.

For example, if you want to substitute the value 1 for the word “TRUE” and the value 0 for the word “FALSE,” you would declare these two #define statements:

#define TRUE 1 #define FALSE 0

This will cause the compiler to substitute a 1 or a 0 each time the word TRUE or FALSE is encountered.

The #define directive has another feature: the macro can have arguments. A macro that takes arguments acts much like a function. In fact, this type of macro is often referred to as a function-like macro. Each time the macro is encountered, the arguments associated with it are replaced by the actual arguments found in the program. For example,

#include <iostream> using namespace std; #define ABS(a) ((a)<0 ? -(a) : (a)) int main() {   cout << "abs of -1 and 1: " << ABS(-1)         << ' ' << ABS(1);   return 0; }

When this program is compiled, a in the macro definition will be substituted with the values –1 and 1.

In C++ and C99, inline functions have reduced the need for function-like macros.

Programming Tip 

You must be sure to completely parenthesize function-like macros that you create. If you don’t, they may not work in all situations. For example, the parentheses surrounding a in the preceding example are necessary to ensure proper substitution in all cases. If the parentheses around a were removed, the expression

ABS (10-20)

Would be converted to

 10-20<0 ? –10-20 : 10-20 

thus yielding the wrong result. If you have a function-like macro that misbehaves, check your parentheses.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: