Sams Teach Yourself C++ in 21 Days

(singke) #1
What’s Next 753

21


Using #definefor Constants..........................................................................


One way to use #defineis as a substitute for constants. This is almost never a good idea,
however, because #definemerely makes a string substitution and does no type checking.
As explained in the section on constants, tremendous advantages exist in using the const
keyword rather than #define.


Using #definefor Tests ................................................................................


A second way to use #defineis simply to declare that a particular character string is
defined. Therefore, you could write


#define DEBUG


Later in your listing, you can test to determine whether BIGhas been defined and take
action accordingly. To check if it is defined, you can use the preprocessor #ifcommand
followed by the definedcommand:


#if defined DEBUG
cout << Debug defined”;
#endif


The definedexpression evaluates to true if the name it tests—DEBUGin this case—has
been defined already. Keep in mind that this happens in the preprocessor, not in the com-
piler or in the executing program.


When the preprocessor reads the #if defined, it checks a table it has built to see
whether you’ve defined the value that follows. If you have,definedevaluates to true,
and everything between the #if defined DEBUGand its #endifis written into the inter-
mediate file for compiling. If it evaluates to false, nothing between #if defined DEBUG
and #endifis written into the intermediate file; it is as if it were never in the source code
in the first place.


A shortcut directive also exists for checking defined values. This is the #ifdefdirective:


#ifdef DEBUG
cout << “Debug defined”;
#endif


You can also test to see if a value is not defined. This is done by using the notoperator
with the defineddirective:


#if !defined DEBUG
cout << “Debug is not defined”;
#endif


There is also a shortcut version for this as well,#ifndef:

Free download pdf