Assertions
Runtime Assert
Use assert to check invariants at runtime. If the condition is false, the program prints an error and raises an exception:
int SafeDivide(int a, int b){ assert(b != 0, "divisor must not be zero"); return a / b;}An optional message string provides context on failure:
assert(x > 0); // default messageassert(x > 0, "x must be positive"); // custom messageMultiple Assertions
Chain multiple asserts to validate preconditions:
int Add(int a, int b){ assert(a >= 0, "a must be non-negative"); assert(b >= 0, "b must be non-negative"); return a + b;}Release-Mode Stripping
Runtime asserts are automatically stripped in release builds (when safety_checks is disabled). The compiler still validates the syntax but emits no code, so asserts have zero cost in production.
Debugger Support
When an assert fails:
- Native debuggers (Visual Studio, WinDbg) break at the assert site automatically
- Cera debugger (DAP) stops with an
"exception"reason, allowing you to inspect variables and the call stack
Const Assert
const assert evaluates the condition at compile time. A false condition produces a compile error:
const assert(true); // OK — passes silentlyconst assert(true, "should pass"); // OK — message ignored on successconst assert(false); // Compile error: Const assertion failed.const assert(false, "bad value"); // Compile error: Const assertion failed: bad valueThe condition must be a compile-time constant (true or false literal). Non-constant expressions are rejected:
int x = 1;const assert(x == 1); // Compile error: condition must be a compile-time constantSyntax Summary
| Form | When | Behavior on Failure |
|---|---|---|
assert(cond) | Runtime | Exception with default message |
assert(cond, "msg") | Runtime | Exception with custom message |
const assert(cond) | Compile time | Compile error |
const assert(cond, "msg") | Compile time | Compile error with message |
See Also
- Error Handling —
try/catch/throwfor recoverable errors - Const Evaluation — compile-time evaluation system