assert
Header: <cassert>
The definition of the macro assert depends on another macro, NDEBUG, which is not defined by the standard library.
# Declarations
Disabled assertion
#define assert(condition) ((void)0)
(until C++26)
#define assert(...) ((void)0)
(since C++26)
Enabled assertion
#define assert(condition) /* unspecified */
(until C++26)
#define assert(...) /* unspecified */
(since C++26)
# Parameters
condition: expression of scalar type
# Notes
Because assert is a function-like macro, commas anywhere in the argument 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.
Since C++20, the values needed for the diagnostic message can also be obtained from std::source_location::current().
Even though the change of assert in C23/C++26 is not formally a defect report, the C committee recommends implementations to backport the change to old modes.
# 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
}
# Defect reports
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 2234 | C++11 | assert could not be used in constant expression | can be used |