1# JSON_ASSERT 2 3```cpp 4#define JSON_ASSERT(x) /* value */ 5``` 6 7This macro controls which code is executed for [runtime assertions](../../features/assertions.md) of the library. 8 9## Parameters 10 11`x` (in) 12: expression of scalar type 13 14## Default definition 15 16The default value is [`#!cpp assert(x)`](https://en.cppreference.com/w/cpp/error/assert). 17 18```cpp 19#define JSON_ASSERT(x) assert(x) 20``` 21 22Therefore, assertions can be switched off by defining `NDEBUG`. 23 24## Notes 25 26- The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior 27 (e.g., when calling [operator[]](../basic_json/operator%5B%5D.md) with a missing object key on a `const` object). See 28 page [runtime assertions](../../features/assertions.md) for more information. 29- Defining the macro to code that does not call `std::abort` may leave the library in an undefined state. 30- The macro is undefined outside the library. 31 32## Examples 33 34??? example "Example 1: default behavior" 35 36 The following code will trigger an assertion at runtime: 37 38 ```cpp 39 #include <nlohmann/json.hpp> 40 41 using json = nlohmann::json; 42 43 int main() 44 { 45 const json j = {{"key", "value"}}; 46 auto v = j["missing"]; 47 } 48 ``` 49 50 Output: 51 52 ``` 53 Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. 54 ``` 55 56??? example "Example 2: user-defined behavior" 57 58 The assertion reporting can be changed by defining `JSON_ASSERT(x)` differently. 59 60 ```cpp 61 #include <cstdio> 62 #include <cstdlib> 63 #define JSON_ASSERT(x) if(!(x)){fprintf(stderr, "assertion error in %s\n", __FUNCTION__); std::abort();} 64 65 #include <nlohmann/json.hpp> 66 67 using json = nlohmann::json; 68 69 int main() 70 { 71 const json j = {{"key", "value"}}; 72 auto v = j["missing"]; 73 } 74 ``` 75 76 Output: 77 78 ``` 79 assertion error in operator[] 80 ``` 81 82## Version history 83 84- Added in version 3.9.0. 85