assert
The definition of the macro assert depends on another macro, NDEBUG , which is not defined by the standard library.
If NDEBUG is defined as a macro name at the point in the source code where <cassert> or <assert.h> is included, then assert does nothing.
If NDEBUG is not defined, then assert checks if its argument (which must have scalar type) compares equal to zero. If it does, assert outputs implementation-specific diagnostic information on the standard error output and calls std::abort . The diagnostic information is required to include the text of expression , as well as the values of the predefined variable __func__ and (since C++11) the predefined macros __FILE__ and __LINE__ .
The expression assert ( E ) is guaranteed to be a constant subexpression, if either
- NDEBUG is defined at the point where assert is last defined or redefined (i.e., where the header <cassert> or <assert.h> was last included); or
- E , contextually converted to bool , is a constant subexpression that evaluates to true .
Contents
[edit] Parameters
condition | — | expression of scalar type |
[edit] Return value
[edit] Notes
Because assert is a function-like macro, commas anywhere in condition that are not protected by parentheses are interpreted as macro argument separators. Such commas are often found in template argument lists and list-initialization:
There is no standardized interface to add an additional message to assert errors. A portable way to include one is to use a comma operator provided it has not been overloaded, or use && with a string literal:
The implementation of assert in Microsoft CRT does not conform to C++11 and later revisions, because its underlying function ( _wassert ) takes neither __func__ nor an equivalent replacement.
Урок №109. assert и static_assert
Использование операторов условного ветвления для обнаружения ложного предположения, а также вывода сообщения об ошибке и завершения выполнения программы является настолько распространенным решением возникающих проблем, что C++ решил это дело упростить. И упростил он его с помощью assert.
Стейтмент assert
Стейтмент assert (или «оператор проверочного утверждения») в языке C++ — это макрос препроцессора, который обрабатывает условное выражение во время выполнения. Если условное выражение истинно, то стейтмент assert ничего не делает. Если же оно ложное, то выводится сообщение об ошибке, и программа завершается. Это сообщение об ошибке содержит ложное условное выражение, а также имя файла с кодом и номером строки с assert. Таким образом, можно легко найти и идентифицировать проблему, что очень помогает при отладке программ.
Сам assert реализован в заголовочном файле cassert и часто используется как для проверки корректности переданных параметров функции, так и для проверки возвращаемого значения функции:
Если в вышеприведенной программе вызвать getArrayValue(array, -3); , то программа выведет следующее сообщение:
Assertion failed: index >= 0 && index <=8, file C:\\VCProjects\\Program.cpp, line 6
Рекомендуется использовать стейтменты assert. Иногда утверждения assert бывают не очень описательными, например:
Если этот assert сработает, то получим:
Assertion failed: found, file C:\\VCProjects\\Program.cpp, line 42
Но что это нам сообщает? Очевидно, что что-то не было найдено, но что именно? Вам нужно будет самому пройтись по коду, чтобы это определить.
К счастью, есть небольшой трюк, который можно использовать для исправления этой ситуации. Просто добавьте сообщение в качестве строки C-style вместе с логическим оператором И:
Как это работает? Строка C-style всегда принимает значение true . Поэтому, если found примет значение false , то false && true = false . Если же found примет значение true , то true && true = true . Таким образом, строка C-style вообще не влияет на обработку утверждения.
Однако, если assert сработает, то строка C-style будет включена в сообщение assert:
Assertion failed: found && «Animal could not be found in database», file C:\\VCProjects\\Program.cpp, line 42
Это даст дополнительное объяснение того, что пошло не так.
NDEBUG
Функция assert() тратит мало ресурсов на проверку условия. Кроме того, стейтменты assert (в идеале) никогда не должны встречаться в релизном коде (потому что ваш код к этому моменту уже должен быть тщательно протестирован). Следовательно, многие разработчики предпочитают использовать assert только в конфигурации Debug. В языке C++ есть возможность отключить все assert-ы в релизном коде — использовать директиву #define NDEBUG :
Некоторые IDE устанавливают NDEBUG по умолчанию, как часть параметров проекта в конфигурации Release.
Обратите внимание, функция exit() и assert (если он срабатывает) немедленно прекращают выполнение программы, без возможности выполнить дальнейшую любую очистку (например, закрыть файл или базу данных). Из-за этого их следует использовать аккуратно.
static_assert
В C++11 добавили еще один тип assert-а — static_assert. В отличие от assert, который срабатывает во время выполнения программы, static_assert срабатывает во время компиляции, вызывая ошибку компилятора, если условие не является истинным. Если условие ложное, то выводится диагностическое сообщение.
Вот пример использования static_assert для проверки размеров определенных типов данных:
C library macro — assert()
The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program.
Declaration
Following is the declaration for assert() Macro.
Parameters
expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
Return Value
This macro does not return any value.
Example
The following example shows the usage of assert() macro −
Let us compile and run the above program in the interactive mode as shown below −
C Language: assert macro
(Assert Truth of Expression)
In the C Programming Language, assert is a macro that is designed to be used like a function. It checks the value of an expression that we expect to be true under normal circumstances.
If expression is a nonzero value, the assert macro does nothing. If expression is zero, the assert macro writes a message to stderr and terminates the program by calling abort.
Syntax
The syntax for the assert macro in the C Language is:
Parameters or Arguments
Required Header
In the C Language, the required header for the assert macro is:
Applies To
In the C Language, the assert macro can be used in the following versions:
- ANSI/ISO 9899-1990
assert Example
Let’s look at an example to see how you would use the assert function in a C program:
When compiled and run, this application will output:
See Also
Other C functions that are noteworthy when dealing with the assert macro: