Поделиться через


Assertions

This topic applies to:

Edition

Visual Basic

C#

F#

C++

Web Developer

Express

Topic does not apply Topic does not apply Topic does not apply

Native only

Topic does not apply

Pro, Premium, and Ultimate

Topic does not apply Topic does not apply Topic does not apply

Native only

Topic does not apply

An assertion statement specifies a condition that you expect to hold true at some particular point in your program. If that condition does not hold true, the assertion fails, execution of your program is interrupted, and the Assertion Failed dialog box appears.

Visual C++ supports assertion statements based on the following constructs:

You can use assertions to:

MFC and C Run-Time Library Assertions

When the debugger halts because of an MFC or C run-time library assertion, it navigates to the point in the source file where the assertion occurred (if the source is available). The assertion message appears in the Output window as well as the Assertion Failed dialog box. You can copy the assertion message from the Output window to a text window if you want to save it for future reference. The Output window may contain other error messages as well. Examine these messages carefully, because they provide clues to the cause of the assertion failure.

Through the liberal use of assertions in your code, you can catch many errors during development. A good rule is to write an assertion for every assumption you make. If you assume that an argument is not NULL, for example, use an assertion statement to check for that assumption.

_DEBUG

Assertion statements compile only when _DEBUG is defined. When _DEBUG is not defined, the compiler treats assertions as null statements. Therefore, assertion statements have zero overhead in your final Release program; you can use them liberally in your code without affecting the performance of your Release version and without having to use #ifdef directives.

Side Effects of Using Assertions

When you add assertions to your code, make sure the assertions do not have side effects. For example, consider the following assertion:

ASSERT(nM++ > 0); // Don't do this!

Because the ASSERT expression is not evaluated in the Release version of your program, nM will have different values in the Debug and Release versions. In MFC, you can use the VERIFY macro instead of ASSERT. VERIFY evaluates the expression but does not check the result in the Release version.

Be especially careful about using function calls in assertion statements, because evaluating a function can have unexpected side effects.

ASSERT ( myFnctn(0)==1 ) // unsafe if myFnctn has side effects
VERIFY ( myFnctn(0)==1 ) // safe

VERIFY calls myFnctn in both the Debug and Release versions, so it is acceptable to use. You will still have the overhead of an unnecessary function call in the Release version, however.

See Also

Reference

Assertions in Managed Code

Concepts

Debugger Security

Other Resources

Debugging Native Code