C assert.h Header

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is assert.h?

<assert.h> is a C standard header that defines the assert macro. Use it to check assumptions during development. If the expression is false (zero), the program prints a diagnostic to stderr and calls abort().

Remember
#include <assert.h>

assert(expression);   // must be true (non-zero)

true  → continue
false → message + abort()

NDEBUG defined → assert becomes a no-op
side effects inside assert → avoid (may vanish)
UsePrefer
Catch programmer bugs in debug buildsassert(...)
Strip checks from release-DNDEBUG
Recoverable user / I/O errorsreturn codes / errno

How to Use assert in C

Include the header, write a clear condition, and keep release builds free of side effects.

  1. Add #include <assert.h> at the top of the file.
  2. Write assert(condition) for an internal invariant (non-null pointer, valid index, precondition).
  3. Compile debug builds without NDEBUG so failures show file and line.
  4. For release, compile with -DNDEBUG so asserts compile out.
PieceRequired?Role
#include <assert.h>YesProvides the assert macro
ExpressionYesMust be non-zero when the program is correct
NDEBUGNoDefine in release to remove all asserts

Pseudocode

Pseudocode
if NDEBUG is defined:
    assert(expr) → do nothing
else:
    if evaluate(expr) is false (zero):
        print diagnostic to stderr  // file, line, expr
        abort()                     // program ends
    else:
        continue

Cheat Sheet

Keep these facts handy while writing debug checks.

TopicDetail
TypeMacro in <assert.h> (not a function)
Syntaxassert(expression);
PassExpression non-zero → no effect
FailMessage to stderr + abort()
Releasegcc -DNDEBUG ... strips asserts
Common checksptr != NULL, n >= 0, i < len
Compile-time cousinstatic_assert (C11 keyword, not this header)

Live Preview

Simulate what assert does: pick a condition and see pass (continue) or fail (diagnostic + abort).

Browser simulation of assert behavior (same idea as the C examples below).

Result
assert(number >= 0);   // number = 25
→ true (non-zero)
→ continue (no abort)

sqrt(25) = 5.00

Worked Walkthrough — Guard sqrt

A helper must reject negative input before calling sqrt. Trace one success and one failure.

Calculation
Function:
  calculate_sqrt(number):
      assert(number >= 0)
      return sqrt(number)

Call 1: calculate_sqrt(25.0)
  number >= 0  →  25 >= 0  →  true
  assert passes → sqrt(25) → 5.0

Call 2: calculate_sqrt(-4.0)
  number >= 0  →  -4 >= 0  →  false
  assert fails → print diagnostic → abort()
  sqrt is never called ✓

C Examples

Compile without NDEBUG to see assertions fire: gcc file.c -std=c11 -g -o out. Link math examples with -lm if needed.

Example 1 — Assert Non-Negative Input for sqrt()

Guard a function precondition: the argument to sqrt must not be negative.

C
#include <assert.h>
#include <math.h>
#include <stdio.h>

double calculate_sqrt(double number) {
    assert(number >= 0);
    return sqrt(number);
}

int main(void) {
    printf("sqrt(25) = %.2f\n", calculate_sqrt(25.0));
    printf("sqrt(-4) = %.2f\n", calculate_sqrt(-4.0));

    return 0;
}

How It Works

  1. Include headers. assert.h for the macro, math.h for sqrt, stdio.h for printf.
  2. First call passes. 25.0 >= 0 is true, so assert does nothing and sqrt(25) prints 5.00.
  3. Second call fails. -4.0 >= 0 is false → diagnostic to stderr and abort().
  4. sqrt never runs on bad input. The assertion stops the bug before undefined or unexpected math behavior.

Example 2 — Assert Pointer Is Not NULL

Document that a pointer argument must be valid before you dereference it.

C
#include <assert.h>
#include <stdio.h>

void print_first(const char *text) {
    assert(text != NULL);
    printf("First char: '%c'\n", text[0]);
}

int main(void) {
    print_first("hello");
    print_first(NULL);

    return 0;
}

How It Works

  1. Check before use. assert(text != NULL) states the contract of print_first.
  2. Valid call. "hello" is non-null → print the first character h.
  3. NULL call. The assertion fails with file and line instead of undefined behavior from text[0].
  4. Debug-only safety. In release with NDEBUG, this check is removed—so never treat assert as your only production guard for untrusted pointers.

Example 3 — assert vs Proper Error Handling

Use return codes for bad user input. Reserve assert for internal guarantees after you already validated the value.

C
#include <assert.h>
#include <stdio.h>

int parse_positive(int n) {
    if (n <= 0) {
        return -1;   /* user error — recoverable */
    }
    assert(n > 0);   /* internal invariant */
    return n * 2;
}

int main(void) {
    printf("parse_positive(5)  = %d\n", parse_positive(5));
    printf("parse_positive(-1) = %d\n", parse_positive(-1));

    return 0;
}

How It Works

  1. Handle bad input first. n <= 0 returns -1 without crashing—good for callers and users.
  2. Assert the invariant. After the if, n must be positive; assert documents that for debug builds.
  3. Success path. parse_positive(5) returns 10.
  4. Error path stays calm. parse_positive(-1) returns -1. Pair this style with errno when wrapping library calls.

Edge Cases & Pitfalls

Check these before relying on assert in real projects.

side effects

Never put side effects in assert

Avoid assert(i++) or assignments inside the expression. With NDEBUG, that code may never run.

users

Not for user input

Bad form data or missing files need return codes or messages—not abort().

release

NDEBUG removes all checks

Production builds often define NDEBUG. Do not rely on assert for security or production validation.

static

Do not confuse with static_assert

static_assert is a C11 compile-time check. Runtime assert lives in this header and fails at run time.

Performance Notes

ApproachCostBest for
Debug assertOne branch (+ string data) per siteDevelopment and tests
Release -DNDEBUGZero (compiled out)Production binaries
Asserts in hot loopsCan slow debug buildsPrefer entry/exit checks

Assertions are cheap compared with I/O. Keep them at function boundaries in debug builds, and strip them with NDEBUG for release.

Key Takeaways

  • Role: debug macro that aborts when an assumption fails.
  • Release: compile with -DNDEBUG to remove asserts.
  • Safety: no side effects inside assert(...).
  • Users: validate input with return codes—not assert.

One line: assert documents “this must be true if my code is correct”—loud in debug, gone in release.

Frequently Asked Questions

assert.h is a standard header that defines the assert macro. assert(expression) checks that expression is true during development. If it is false (zero), the program prints a diagnostic to stderr and calls abort().
assert is a macro, not a function. It expands to code that may include __FILE__ and __LINE__. Do not put side effects inside assert—when NDEBUG is defined, that code may disappear.
Define NDEBUG before including assert.h, or compile with -DNDEBUG. When NDEBUG is defined, assert(expression) expands to a no-op and is removed from the binary.
No. assert is for programmer mistakes and internal invariants. User-facing errors need return codes, errno, or messages—not abort(). Users should never crash your app because of assert.
The implementation writes a diagnostic (expression, file, line) to stderr, then calls abort(). The program ends immediately with no recovery path.
assert checks a runtime expression. static_assert (C11) checks a compile-time condition and fails the build if false. Use static_assert for sizes and constants; use assert for runtime assumptions.

Next: ctype.h

Classify and convert characters with the ctype macros.

ctype.h tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful