Assertions
The assert.h
header provides a simple diagnostic mechanism. Assertions can be performed during compile-time (_Static_assert
keyword) and run-time (assert
macro).
Compile-time
The _Static_assert
keyword evaluates an expression at compile-time.
Code
#include <assert.h> // "static_assert".
#include <stdio.h> // "puts".
int main(void)
{
static_assert (2 + 2 == 4, "Mathematics works."); // Compilation success.
static_assert (sizeof (signed long long int) < sizeof (signed char), "Primitive data type sizes inverted."); // Compilation failure.
puts("Execution success.");
return 0;
}
Compilation
Standard error stream:
In file included from main.c:1:0:
main.c: In function ‘main’:
main.c:7:2: error: static assertion failed: "Primitive data type sizes inverted."
static_assert (sizeof (signed long long int) < sizeof (signed char), "Primitive data type sizes inverted."); // Compilation failure.
^
Run-time
The assert
macro evaluates an expression at run-time.
Debug build
Code
#include <assert.h> // "assert".
#include <stdio.h> // "puts".
int main(void)
{
assert (2 + 2 == 4); // Compilation success.
assert (sizeof (signed long long int) < sizeof (signed char)); // Compilation success, but execution failure.
puts("Execution success.");
return 0;
}
Execution
Standard error stream:
main: main.c:7: main: Assertion `sizeof (signed long long int) < sizeof (signed char)' failed.
Aborted (core dumped)
Release build
Assertions can be disabled for release builds by defining a macro by the name NDEBUG
before the inclusion of the assert
header.
Code
#define NDEBUG
#include <assert.h> // "assert".
#include <stdio.h> // "puts".
int main(void)
{
assert (2 + 2 == 4); // Compilation success.
assert (sizeof (signed long long int) < sizeof (signed char)); // Compilation success.
puts("Execution success.");
return 0;
}
Execution
Standard output stream:
Execution success.