The usage of assert

What is an assertion instruction?

The semantics of the assertion instruction is to judge a certain condition, if the result is not true, perform an unconventional action, generally the program ends immediately.

Several common assertion instructions

1. The assert
condition fails to terminate the operation.
2. The verify
condition fails to continue execution and an error is output.
3. Waitfor
and other conditions are loaded successfully before continuing down execution, otherwise it has been waiting.

The specific use and precautions of C/C++ assertion instruction

The prototype of the assert macro is defined in assert.h, and its function is to terminate the program execution if its condition returns an error.

#include "assert.h" 
void assert( int expression );

The function of assert is to judge the return value of expression. If its value is false (ie 0), then it first prints an error message to stderr, and then terminates the program by calling abort.

The disadvantage of using assert is that frequent calls will greatly affect the performance of the program and increase additional overhead.

**Note:** Programs are generally divided into Debug version and Release version. The Debug version is used for internal debugging, and the Release version is issued to users. Assert Assert is a macro that works only in the Debug version. It is used to check what "should not" happen. The following is a memory copy program. During operation, if the parameter of assert is false, the program will be terminated (generally, a prompt dialog will appear to explain where the assert is triggered).

to sum up

Assertions are a debugging method. If an assertion fails, an error warning will be thrown and the program will be terminated. Assertions can only be enabled during the development and testing phases;

Assertions cannot be used for recoverable errors, but exceptions should be thrown;

Assertions are rarely used, and a better way is to write unit tests.

Guess you like

Origin blog.csdn.net/daijingxin/article/details/114273498