Ad space (banner)
๐Ÿ”งC Lessons
Lesson 28 / 68

Checking Correctness with the assert Macro (Your First Step into Testing)

This lesson covers writing a simple test in C using the assert macro, your first step toward the habit of verifying a program's correctness. It's for anyone searching "C assert usage."

assert(condition) is a macro that abnormally terminates the program and lets you know when a condition is false. It's the basic idea behind test code โ€” automatically checking "does this function's result match what I expect."

The example confirms the expected and actual results match in a single line, assert(add(2, 3) == 5). When the condition is false, the program prints a message and stops.

A common early mistake is not knowing assert can be disabled in a release build. When a macro called NDEBUG is defined, assert's contents don't run at all โ€” so it can't be a substitute for real error handling in production.

In real projects, using assert as a debugging aid during development, and implementing separate, proper error handling for production, is the standard approach.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)