|
|
 |
|
|
|
|
6: #define ASSERT(x)
7: #else
8: #define ASSERT(x) \
9: if (! (x)) \
10: { \
11: cout << ERROR!! Assert << #x << failed\n; \
12: cout << on line << __LINE__<< \n; \
13: cout << in file << __FILE__ << \n; \
14: }
15: #endif
16:
17:
18: int main()
19: {
20: int x = 5;
21: cout << First assert: \n;
22: ASSERT (x==5);
23: cout << \nSecond assert: \n;
24: ASSERT (x != 5);
25: cout << \nDone.\n;
26: return 0;
27: } |
|
|
|
|
|
|
|
|
Output:First assert:
Second assert:
ERROR!! Assert x!=5 failed
on line 24
in file test2103.cpp |
|
|
|
|
|
|
|
|
Analysis: On line 2, the term DEBUG is defined. Typically, this would be done from the command line (or the IDE) at compile time, so that you could turn it on and off at will. On lines 815, the assert() macro is defined. Typically, this would be done in a header file, and that header (ASSERT .HPP) would be included in all your implementation files. |
|
|
|
|
|
|
|
|
On line 5, the term DEBUG is tested. If it is not defined, assert() is defined to create no code at all. If DEBUG is defined, the functionality defined on lines 814 is applied. |
|
|
|
|
|
|
|
|
The assert() itself is one long statement, split across seven source code lines, as far as the precompiler is concerned. On line 9, the value passed in as a parameter is tested; if it evaluates false, the statement on lines 1113 are invoked, printing an error message. If the value passed in evaluates true, no action is taken. |
|
|
|
|
|