The ASSERT macro evaluates its argument, prints a diagnostic message, and halts program execution if the argument expression is false (0). The diagnostic message is sent to afxDump and has the form
assertion failed in file <name> in line <num>
where <name> is the name of the source file and <num> is the line number of the assertion that failed in the source file. The ASSERT macro takes no action if its argument is true (nonzero).
The ASSERT macro is typically used to identify program errors during development. The argument given to ASSERT should be chosen so that it holds true only if the program is operating as intended. The following example shows how the ASSERT macro could be used to check the validity of a function's return value:
int x = SomeFunc(y);
ASSERT(x == 0); // ASSERT only if x not equal to 0
ASSERT can also be used in combination with the IsKindOf macro to provide extra checking for function arguments, such as in the following example. (For a discussion of the IsKindOf macro, see “How to Access Run-time Class Information” on page 265).
ASSERT( object1->IsKindOf( RUNTIME_CLASS( CPerson ) ) );
Like the TRACE macro described in the previous section, the ASSERT macros are only active in the Debug version of your program. Thus, you can inactivate all ASSERT statements simply by building the Release version of your program.
Using assertions liberally throughout your programs can catch errors during development. A good rule of thumb is that you should write assertions for any assumptions you make. For example, if you assume that an argument is not NULL, then you should use an assertion statement to check for that condition. The good thing about the ASSERT macro is that it will catch errors when you are using the Debug version of the Microsoft Foundation Class Library during development but will be turned off (produce no code) when you build your program with the Release version of the library.
Note:
The expression argument to ASSERT will not be executed in the release version of your program. If you want the expression to be executed in both debug and release environments, use the VERIFY macro instead of ASSERT. In debug versions, VERIFY simply passes its expression argument to ASSERT. In release environments, VERIFY executes the expression argument but does not check the result.