C language - assert assert

 1. assert is a macro, not a function .

2.assert(), if the expression in the brackets is 0 (false) , write the message to the standard error device and call the function abort(), report an error and terminate the program execution. Otherwise assert has no effect.

example:

#include<assert.h>
#include<stdio.h>
void fun(char* dest, char* src)
{
	while (*dest++ = *src++)`
	{
		;
	}
}


int main()
{
	char arr[20] = { 0 };
	char* p = NULL;
	fun(arr, p);
	return 0;
}

 

 Dereferencing a null pointer results in an error.

To judge the validity of pointers and expose errors, we use assert .

#include<assert.h>
#include<stdio.h>
void fun(char* dest, char* src)
{
//每个assert最好只检验一个条件,因为同时检验多个条件时,
//如果断言失败,无法直观的判断是哪个条件失败。
	assert(src != NULL);
    assert(dest !=NULL);
	while (*dest++ = *src++)
	{
		;
	}
}


int main()
{
	char arr[20] = { 0 };
	char* p = NULL;
	fun(arr, p);
	return 0;
}

It is best to test only one condition for each assert, because when multiple conditions are tested at the same time, if the assertion fails, it is impossible to intuitively judge which condition failed. 

Quickly locate the error .

3. After debugging, you can disable the assert call by inserting #define NDEBUG before the statement containing #include <assert.h>.

 4. assert(), optimized in the release version

5. Header file

Guess you like

Origin blog.csdn.net/outdated_socks/article/details/129656940
Recommended