2022-07-28 18:46:13 +00:00
|
|
|
|
|
|
|
# assert.h - debug assertions
|
|
|
|
|
|
|
|
Macro definitions:
|
|
|
|
|
|
|
|
- [`assert(expr)`](#assert)
|
|
|
|
- [`static_assert`](#static-assert)
|
|
|
|
|
|
|
|
## [assert](#assert)
|
|
|
|
|
|
|
|
Assert a given condition is true, otherwise abort execution of a program.
|
|
|
|
|
|
|
|
The macro checks whether `expr` is true, and if not, prints the
|
2022-07-30 02:06:35 +00:00
|
|
|
diagnostic information and then aborts execution in a way equivalent to calling
|
|
|
|
abort() function (See SIGABRT).
|
2022-07-28 18:46:13 +00:00
|
|
|
|
2022-08-07 09:41:49 +00:00
|
|
|
If `_DEBUG` macro is defined, assert does not print a diagnostic message, and
|
2022-07-30 02:06:35 +00:00
|
|
|
instead simply causes a debug break.
|
2022-07-28 18:46:13 +00:00
|
|
|
|
2022-07-30 02:06:35 +00:00
|
|
|
If NDEBUG macro is defined assert expands to an empty statement. If both NDEBUG
|
2022-08-07 09:41:49 +00:00
|
|
|
and `_DEBUG` are defined, then `_DEBUG` macro is ignored.
|
2022-07-28 18:46:13 +00:00
|
|
|
|
|
|
|
```c
|
|
|
|
#if defined(NDEBUG)
|
|
|
|
#define assert(expr) ((void)0)
|
2022-08-07 09:41:49 +00:00
|
|
|
#elif defined(`_DEBUG`)
|
2022-07-30 02:06:35 +00:00
|
|
|
#define assert(expr) /* debug break */
|
2022-07-28 18:46:13 +00:00
|
|
|
#else
|
2022-07-30 02:06:35 +00:00
|
|
|
#define assert(expr) /* print diagnostic, then abort */
|
2022-07-28 18:46:13 +00:00
|
|
|
#endif
|
|
|
|
```
|
|
|
|
|
|
|
|
<details>
|
|
|
|
<summary>Example</summary>
|
|
|
|
|
|
|
|
```c
|
|
|
|
// Uncomment to disable assert
|
|
|
|
//#define NDEBUG
|
|
|
|
#include <assert.h>
|
|
|
|
|
|
|
|
int factorial(int n) {
|
|
|
|
assert(n >= 0);
|
|
|
|
if(n == 0) return 1;
|
|
|
|
return n*factorial(n-1);
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
printf("Factorial of %d is %d\n", 10, factorial(10));
|
|
|
|
printf("Factorial of %d is %d\n", -1, factorial(-1));
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
The first function would print 3628800, the second would trigger an assert.
|
|
|
|
Output:
|
|
|
|
|
|
|
|
```
|
|
|
|
Factorial of 10 is 3628800
|
|
|
|
Assertion failed: n >= 0
|
|
|
|
Function: factorial
|
|
|
|
File: test\test_assert.c
|
|
|
|
Line: 4
|
|
|
|
Trace:
|
|
|
|
4: factorial
|
|
|
|
3: main
|
|
|
|
2: mainCRTStartup
|
|
|
|
1: BaseThreadInitThunk
|
|
|
|
0: RtlUserThreadStart
|
|
|
|
```
|
|
|
|
</details>
|
|
|
|
|
|
|
|
## [static_assert](#static-assert)
|
|
|
|
|
|
|
|
Keyword macro that expands to C11 keyword `_Static_assert`.
|
|
|
|
|
|
|
|
```c
|
|
|
|
#define static_assert _Static_assert
|
|
|
|
```
|