Bird
Raised Fist0
CHow-ToBeginner · 3 min read

How to Use assert in C for Debugging and Validation

In C, use the assert macro from <assert.h> to test assumptions in your code. If the condition inside assert is false, the program prints an error message and stops immediately.
📐

Syntax

The assert macro checks a condition you provide. If the condition is false, it prints an error message with the file name and line number, then stops the program.

Include <assert.h> to use assert.

  • assert(expression); - where expression is what you want to check.
c
#include <assert.h>

int main() {
    assert(expression);
}
💻

Example

This example shows how assert stops the program if a condition is false. It checks if a number is positive.

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

int main() {
    int number = -5;
    assert(number > 0);  // This will fail because number is negative
    printf("Number is positive\n");
    return 0;
}
Output
Assertion failed: (number > 0), function main, file example.c, line 7.
⚠️

Common Pitfalls

Common mistakes when using assert include:

  • Using assert for runtime error handling instead of debugging.
  • Not including <assert.h> before using assert.
  • Expecting assert to run in release builds; it is disabled if NDEBUG is defined.

Use assert only to catch programming errors during development, not for user input validation.

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

// Wrong: assert used for user input validation
int divide(int a, int b) {
    assert(b != 0);  // This will be removed in release builds
    return a / b;
}

// Right: handle errors explicitly
int safe_divide(int a, int b) {
    if (b == 0) {
        printf("Error: division by zero\n");
        return 0; // or handle error properly
    }
    return a / b;
}
📊

Quick Reference

  • Include: <assert.h>
  • Syntax: assert(expression);
  • Behavior: Stops program if expression is false
  • Disabled: When NDEBUG is defined (usually in release builds)
  • Use case: Debugging, checking assumptions, not for user input validation
✅

Key Takeaways

Use assert to check conditions that must always be true during development.
assert stops the program and shows an error if the condition is false.
Include <assert.h> to use assert.
assert is disabled in release builds if NDEBUG is defined.
Do not use assert for handling user input or runtime errors.