skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
h-assert
This page is read only. You can view the source, but not change it.
# <assert.h> **[<assert.h>](https://en.cppreference.com/w/c/header/assert)** provides the `assert` macro for runtime checking during development. It evaluates a condition and terminates the program with a diagnostic message showing the file, line, and failed condition if it's false. Assertions are stripped entirely when compiled with `-DNDEBUG`, so they cost nothing in release builds. Never put side effects in assertions—they won't execute in production. ## Example This example uses assertions to check preconditions, which can be completely removed in release builds. ```c // compile: gcc -o assertexample assertexample.c // run: ./assertexample // description: assertions fire on invalid input; -DNDEBUG disables them entirely #include <assert.h> #include <stdio.h> int divide(int a, int b) { assert(b != 0); return a / b; } int main() { printf("%d\n", divide(10, 2)); printf("%d\n", divide(10, 0)); // assertion fires return 0; } ``` ## Common macros **Runtime assertions**: - `assert(condition)`: if condition is false, print diagnostic and abort: - Message format: `Assertion failed: (condition), file filename, line N` - Writes to stderr - Terminates with abort() **Disabling assertions**: - `NDEBUG`: preprocessor symbol; define before including `<assert.h>` to disable all assertions - Compile with `-DNDEBUG` to remove assertions - In release builds, assertions cost nothing (zero overhead) **Usage patterns**: - Check **preconditions** on entry (e.g., pointer not NULL) - Check **invariants** that must hold (e.g., array index in bounds) - Never put **side effects** in assertions (e.g., `assert(i++ < 10)`: the increment won't happen in release) - Use for debugging; for user error handling use exceptions or error codes
Page Tools
Show pagesource
Backlinks
Back to top