C assert assert() Macro
Example
Check that a number is not 0 before you divide by it:
int divide(int a, int b) {
assert(b != 0);
return a / b;
}
int main() {
printf("%d", divide(10, 2));
return 0;
}
Definition and Usage
The assert() macro checks a condition while the program runs.
If the condition is false, it prints an error message with the condition, the file name and the line number, and then stops the program. In the example, divide(10, 0) would stop the program with a message like Assertion `b != 0' failed.
Use assert() to find mistakes in your own code while you test it. Do not use it to check user input, because the checks can be turned off.
If NDEBUG is defined before <assert.h> is included, assert() does nothing (see More Examples below).
The assert() macro is defined in the <assert.h> header file.
Syntax
assert(expression);
Parameter Values
| Parameter | Description |
|---|---|
| expression | Required. A condition that should be true. If it is false (0), the program prints an error message and stops. |
More Examples
Example
Turn off all assert() checks with NDEBUG:
#define NDEBUG
#include <stdio.h>
#include <assert.h>
int main() {
int age = -5;
assert(age >= 0);
printf("%d", age);
return 0;
}
Related Pages
Read more about finding mistakes in our C Debugging Tutorial.