What’s Next 761
21
precompiled, not when the program is run. If you ask the program to print __DATE__,
you do not get the current date; instead, you receive the date the program was compiled.
These defined macros are very useful in debugging, as mentioned on Day 20, “Handling
Errors and Exceptions,” during the discussion of exceptions.
The assert()Macro............................................................................................
Many compilers offer an assert()macro. The assert()macro returns trueif its para-
meter evaluates to true and takes some kind of action if it evaluates false. Many compil-
ers abort the program on an assert()that fails; others throw an exception (see Day 20).
The assert()macro is used for debugging your program before you release it. In fact, if
DEBUGis not defined, the preprocessor collapses the assert()so that no code from it is
included in the generated source for the compiler. This is a great help during develop-
ment, and when the final product ships, there is no performance penalty or increase in
the size of the executable version of the program.
Rather than depending on the compiler-provided assert(), you are free to write your
own assert()macro. Listing 21.3 provides a simple custom assert()macro and shows
its use.
LISTING21.3 A Simple assert()Macro
0: // Listing 21.3 ASSERTS
1: #define DEBUG
2: #include <iostream>
3: using namespace std;
4:
5: #ifndef DEBUG
6: #define ASSERT(x)
7: #else
8: #define ASSERT(x) \
9: if (! (x)) \
10: { \
11: cout << “ERROR!! Assert “ << #x << “ failed << endl; \
12: cout << “ on line “ << __LINE__ << endl; \
13: cout << “ in file “ << __FILE__ << endl; \
14: }
15: #endif
16:
17: int main()
18: {
19: int x = 5;
20: cout << “First assert: “ << endl;
21: ASSERT(x==5);