|
|
|
|
|
|
|
A second way to use #define, however, is simply to declare that a particular character string is defined. Therefore, you could write |
|
|
|
|
|
|
|
|
Later, you can test whether BIG has been defined and take action accordingly. The precompiler commands to test whether a string has been defined are #ifdef (to see whether the string has been defined) and #ifndef (to test whether it has not been defined). Both of these must be followed by the command #endif before the block ends (before the next closing brace). |
|
|
|
|
|
|
|
|
#ifdef evaluates to true if the string it tests has been defined already. Therefore, you can write this: |
|
|
|
|
|
|
|
|
#ifdef DEBUG
cout << Debug defined;
#endif |
|
|
|
|
|
|
|
|
When the precompiler reads the #ifdef, it checks a table it has built to see if you've defined DEBUG. If so, the #ifdef evaluates to true, and everything to the next #else or #endif is written into the intermediate file for compiling. If it evaluates to false, nothing between #ifdef DEBUG and the next #else or #endif will be written into the intermediate file; it will be as if it were never in the source code in the first place. |
|
|
|
|
|
|
|
|
Note that #ifndef is the logical reverse of #ifdef. #ifndef evaluates to true if the string has not been defined up to that point in the file. |
|
|
|
|
|
|
|
|
The #else Precompiler Command |
|
|
|
|
|
|
|
|
As you might imagine, the term #else can be inserted between either #ifdef or #ifndef and the closing #endif. Listing 21.1 illustrates how all these terms are used. |
|
|
|
|
|
|
|
|
LISTING 21.1 USING#define |
|
|
|
 |
|
|
|
|
1: #define DemoVersion
2: #define DOS_VERSION 5
3: #include <iostream.h>
4:
5:
6: int main()
7: {
8:
9: cout << Checking on the definitions of DemoVersion, |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|