Writing a simple assert() check
What you'll learn: How to use the assert() macro to catch bugs early by verifying that your program’s data remains within expected boundaries.
The Safety Net of Programming
Imagine you are building a bridge. You design it to hold 10,000 pounds. To be safe, you install an automated sensor: the moment a vehicle heavier than that limit touches the pavement, the bridge physically locks down and sounds an alarm. You’d rather stop everything immediately than let the bridge collapse.
In C, the assert() macro is that sensor. It is a "sanity check" that confirms a specific condition is true. If the condition is true, the program carries on as if nothing happened. If it’s false, the program stops instantly and tells you exactly which line of code failed.
How to use assert()
To use this tool, you must include the <assert.h> header. The syntax is straightforward: assert(expression);.
Commonly, we use it to check things that should never happen if our logic is correct—like a denominator being zero, a pointer being null, or an age being a negative number.
#include <stdio.h>
#include <assert.h>
void calculate_pantry_space(int cans) {
// A pantry cannot have "negative" cans.
// If this happens, our logic elsewhere is broken.
assert(cans >= 0);
printf("You have %d cans in the pantry.\n", cans);
}
int main() {
int current_stock = 25;
calculate_pantry_space(current_stock); // This works fine!
// Simulating a logic error elsewhere in the code
current_stock = -5;
printf("Checking stock again...\n");
calculate_pantry_space(current_stock); // This will trigger the assert!
return 0;
}
Why stop the program?
You might wonder: "Isn't crashing bad?" In a finished product, yes. But during the testing phase, crashing is a gift.
If current_stock becomes -5, your program is in a "corrupt" state. If you let it keep running, that error might travel through your code like a virus, causing weird glitches minutes later that are impossible to trace. By using assert(), you catch the thief at the door rather than trying to find them after they've moved all the furniture.
Key takeaway
Use assert() to define "impossible" conditions; it turns hidden logic errors into loud, immediate notifications that tell you exactly where your code went wrong.