C++ assert and NDEBUG

assert() assertion mechanism principle and use

1 Introduction

assert is a preprocessing macro.
The function of assert is to calculate the expression expression, if its value is false (that is, 0), then it first prints an error message to stderr, and then terminates the program by calling abort.

void analyze_string( char * string )
{
    
    
   assert( string != NULL );        // Cannot be NULL
   assert( *string != '\0' );       // Cannot be empty
   assert( strlen( string ) > 2 );  // Length must exceed 2
}

2. Usage summary and precautions:

1. Check the validity of the incoming parameters at the beginning of the function. For example,
2. Each assert only checks one condition, because when multiple conditions are checked at the same time, if the assertion fails, it is impossible to intuitively judge which condition failed. 3. Change cannot be
used The statement of the environment, because assert only takes effect in DEBUG, if you do this, you will
encounter problems when the program is actually running .
5. In some places, assert cannot replace conditional filtering.

assert is for avoiding obvious mistakes, not for handling exceptions. Errors and exceptions are not the same, errors should not occur, exceptions are inevitable. C language exceptions can be handled through conditional judgment, and other languages ​​have their own exception handling mechanisms.
A very simple rule of using assert is that it is used at the beginning of a method or function. If it is used in the middle of a method, it needs to be carefully considered whether it should be used. At the beginning of the method, a functional process has not yet started, and the problems that occur during the execution of a functional process are almost all abnormal

NDEBUG preprocessing variable

1. The NDEBUG macro definition can affect the behavior of assert, which is not defined by default. When we define NDEBUG in a macro,
  the function of assert is blocked

2. We can use a #define statement to define NDEBUG to turn off the debugging state.

__func__        	//局部静态变量,存放函数的名字
__LINE__            //存放当前行号的整型字面值
__FILE__            //存放文件名的字符串字面值
__TIME__            //存放文件编译时间的字符串字面值
__DATE__            //存放文件编译日期的字符串字面值

Guess you like

Origin blog.csdn.net/Algabeno/article/details/123555399