CodeBlanks Logo Icon CodeBlanks

assert

  • C course
  • Intermediate
  • Lesson 56/116
  • 5 min

Learn debug checks with assert.

The assert macro

The assert macro checks a condition; if false, it stops the program and prints an error. Usage: assert(ptr != NULL);. You need <assert.h>. When the condition is false, it calls abort with the source file and line number.

assert is a debugging tool; it catches unexpected states. If the NDEBUG macro is defined, assert does nothing; so production builds can disable it. It's not for error handling but for programmer errors (precondition violations).

assert and function calls

Don't put a function with side effects inside assert. Example: assert(allocate() != NULL); — with NDEBUG, allocate is never called, behavior changes. The right way: call first, then check.

assert's message includes file, line and the condition; you don't need an extra message. C99 added static_assert for compile-time checks, also usable as _Static_assert. For runtime checks you still use assert.

Practice Add a precondition with assert

Include <stdio.h> and <assert.h>. Write int divide(int a, int b) that calls assert(b != 0); and returns a / b;. In main, print printf("%d\n", divide(10, 2));.

Starter code

main.c
#include <stdio.h>
// Include assert.h

// Write divide: precondition and division

int main(void) {
    // Call divide(10, 2) and print
    return 0;
}

Sample solution

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

int divide(int a, int b) {
    assert(b != 0);
    return a / b;
}

int main(void) {
    printf("%d\n", divide(10, 2));
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which macro disables assert?

  • DEBUG
  • NDEBUG Correct answer
  • RELEASE
  • ASSERT

Explanation: With NDEBUG defined, assert does nothing.

2 Complete the assert call

Question
#include <assert.h>
void set_age(int age) {
    ____(age >= 0);
}
Answer
#include <assert.h>
void set_age(int age) {
    assert(age >= 0);
}

Explanation: assert(age >= 0) catches negative ages.

3 Match assert usage patterns

Term Meaning
assert(ptr != NULL) Precondition check
NDEBUG Disables assert
abort assert calls it
assert.h Required header

All lessons in Intermediate