2.2 KiB
2.2 KiB
JSON_ASSERT
#define JSON_ASSERT(x) /* value */
This macro controls which code is executed for runtime assertions of the library.
Parameters
x(in)- expression of a scalar type
Default definition
The default value is #!cpp assert(x).
#define JSON_ASSERT(x) assert(x)
Therefore, assertions can be switched off by defining NDEBUG.
Notes
- The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior
(e.g., when calling operator[] with a missing object key on a
constobject). See page runtime assertions for more information. - Defining the macro to code that does not call
std::abortmay leave the library in an undefined state. - The macro is undefined outside the library.
Examples
??? example "Example: default behavior"
The following code will trigger an assertion at runtime:
```cpp
#include <nlohmann/json.hpp>
using nlohmann::json;
int main()
{
const json j = {{"key", "value"}};
auto v = j["missing"];
}
```
The assertion `#!cpp it != m_data.m_value.object->end()` fails in `#!cpp operator[]`.
The exact diagnostic format, source filename, and line number depend on the platform,
library version, and whether the single-header or multi-header version is used.
??? example "Example: user-defined behavior"
The assertion reporting can be changed by defining `JSON_ASSERT(x)` differently.
```cpp
#include <cstdio>
#include <cstdlib>
#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, "assertion error in %s\n", __FUNCTION__); std::abort();}
#include <nlohmann/json.hpp>
using nlohmann::json;
int main()
{
const json j = {{"key", "value"}};
auto v = j["missing"];
}
```
Output:
```
assertion error in operator[]
```
See also
- Runtime Assertions - overview documentation
- Supported Macros - guide to all supported macros
Version history
- Added in version 3.9.0.