Skip to content

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 message
assert(x > 0, "x must be positive"); // custom message

Multiple 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 silently
const assert(true, "should pass"); // OK — message ignored on success
const assert(false); // Compile error: Const assertion failed.
const assert(false, "bad value"); // Compile error: Const assertion failed: bad value

The 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 constant

Syntax Summary

FormWhenBehavior on Failure
assert(cond)RuntimeException with default message
assert(cond, "msg")RuntimeException with custom message
const assert(cond)Compile timeCompile error
const assert(cond, "msg")Compile timeCompile error with message

See Also