Brief analysis of the use of assert in C language

  • 2020-04-02 01:08:34
  • OfStack

The assert macro prototype is defined in < Assert. H > If its condition returns an error, the execution of the program is terminated.
# include < Assert. H >
Void assert(int expression);
An assert is used to evaluate the expression. If it is false (that is, 0), it first prints an error message to stderr.
Then abort is called to abort the program.
See the program listing badptr.c below:


#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
int main( void )
{
       FILE *fp;

       fp = fopen( "test.txt", "w" );//Open a file in a writable manner and create a file with the same name if it does not exist
       assert( fp );                           //So you can't go wrong here
       fclose( fp );

       fp = fopen( "noexitfile.txt", "r" );//Open a file in a read-only manner. Failure to open the file if it does not exist
       assert( fp );                           //So there's an error here
       fclose( fp );                           //The program will never execute here
       return 0;
}

Macro name: assert
Power: to test a condition and possibly terminate a program
Void assert(int test); void assert(int test);
Application:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct ITEM {
  int key;
  int value;
};


void additem(struct ITEM *itemptr) {
  assert(itemptr != NULL);
  
}

int main(void)
{
  additem(NULL);
  return 0;
}

The assert () macro usage
Note: assert is a macro, not a function. In the assert. H header file of C.
The assert macro prototype is defined in < Assert. H > If its condition returns an error, the execution of the program is terminated.

#include <assert.h>
void assert( int expression );

An assert is used to evaluate an expression first expression , if its value is false (that is, 0), it flows first to the standard error stream stderr Print an error message, and then pass the call abort To terminate the program; Otherwise, assert() does nothing. The macro assert () is generally used to confirm the normal operation of a program, where the expression is true only when it is constructed correctly. After debugging, you don't have to remove the assert() statement from the source code because the macro assert() is defined as null when the macro NDEBUG is defined.


Related articles: