On this page
assert
Defined in header <cassert> |
||
---|---|---|
Disabled assertion | ||
(1) | ||
|
(until C++26) | |
|
(since C++26) | |
Enabled assertion | ||
(2) | ||
|
(until C++26) | |
|
(since C++26) |
The definition of the macro assert
depends on another macro, NDEBUG
, which is not defined by the standard library.
NDEBUG
is defined as a macro name at the point in the source code where <cassert>
or <assert.h> is included, the assertion is disabled: assert
does nothing.
|
(until C++26) |
|
(since C++26) |
The expression
|
(since C++17) |
Parameters
condition | - | expression of scalar type |
Return value
(none)
Notes
Because
|
(until C++26) |
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:
assert(("There are five lights", 2 + 2 == 5));
assert( (2 + 2 == 5) && "There are five lights");
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.
Example
#include <iostream>
// uncomment to disable assert()
// #define NDEBUG
#include <cassert>
// Use (void) to silence unused warnings.
#define assertm(exp, msg) assert(((void)msg, exp))
int main()
{
assert(2 + 2 == 4);
std::cout << "Checkpoint #1\n";
assert((void("void helps to avoid 'unused value' warning"), 2 * 2 == 4));
std::cout << "Checkpoint #2\n";
assert((010 + 010 == 16) && "Yet another way to add an assert message");
std::cout << "Checkpoint #3\n";
assertm((2 + 2) % 3 == 1, "Success");
std::cout << "Checkpoint #4\n";
assertm(2 + 2 == 5, "Failed"); // assertion fails
std::cout << "Execution continues past the last assert\n"; // No output
}
Possible output:
Checkpoint #1
Checkpoint #2
Checkpoint #3
Checkpoint #4
main.cpp:23: int main(): Assertion `((void)"Failed", 2 + 2 == 5)' failed.
Aborted
See also
static_assert declaration(C++11) |
performs compile-time assertion checking |
causes abnormal program termination (without cleaning up) (function) |
|
C documentation for assert |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/error/assert