assert()

Вывести отладочное сообщение и опционально остановить выполнение программы

Прототип:

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

Аргументы:

expression
Zero if you want to terminate the program; a nonzero value if you don't.

Библиотека:

libc

Описание:

The assert() macro prints a diagnostic message on the stderr stream, and terminates the program, using abort(), if expression is false (0).

The diagnostic message includes the expression, the name of the source file (the value of FILE) and the line number of the failed assertion (the value of LINE).

No action is taken if expression is true (nonzero).

You typically use the assert() macro while developing a program, to identify program logic errors. You should choose the expression so that it's true when the program is functioning as intended.

After the program has been debugged, you can use the special “no debug” identifier, NDEBUG, to remove calls to assert() from the program when it's recompiled. If you use the -D option to qcc or a #define directive to define NDEBUG (with any value), the C preprocessor ignores all assert() calls in the program source.


Note: To remove the calls to assert(), you must define NDEBUG in the code before including the <assert.h> header file (i.e. #include <assert.h>).

If you define NDEBUG, the preprocessor also ignores the expression you pass to assert(). For example, if your code includes:

assert( (fd = open( "filename", O_RDWR )) != -1 );

and you define NDEBUG, the preprocessor ignores the entire call to assert(), including the call to open().


Примеры:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void process_string( char *string )
{
/* use assert to check argument */
assert( string != NULL );
assert( *string != '\0' );
/* rest of code follows here */
}
int main( void )
{
process_string( "hello" );
process_string( "" );
return (EXIT_SUCCESS);
}

Классификация:

ANSI, POSIX 1003.1

Точка остановки потока
Нет
Обработчик прерываний
Нет
Обработчик сигналов
Нет
В потоке
Да

Предостережения:

assert() является макросом.

Тематические ссылки:

abort(), stderr




Предыдущий раздел: Описание API системной библиотеки