C assertions
Created By: chatGPT
In C programming, assertions are a powerful debugging tool that helps ensure that your program behaves as expected. An assertion is a statement that checks a condition at runtime; if the condition evaluates to false, the program will terminate, usually printing an error message indicating where the assertion failed. This is useful for catching bugs during development.
#include <assert.h>
int main() {
int x = 5;
assert(x == 5); // This will pass
assert(x == 10); // This will fail
return 0;
}
The
assert()
macro is defined in the <assert.h>
header file. It takes a single expression. If the expression evaluates to true, the program continues execution; if it evaluates to false, the program asserts and terminates. It's important to remove or disable assertions in production code since they can introduce performance overhead.#include <assert.h>
#include <stdio.h>
int divide(int a, int b) {
assert(b != 0); // Ensure that b is not zero
return a / b;
}
int main() {
int result = divide(10, 2); // This will work
printf("Result: %d\n", result);
result = divide(10, 0); // This will trigger an assertion failure
return 0;
}
To enable assertions, you typically compile your code without defining the NDEBUG macro. If you define NDEBUG, all assertions will be disabled at compile time, and the
assert()
calls will not be included in the final executable. This is often done in release builds to improve performance.// To enable assertions, compile without defining NDEBUG
//#define NDEBUG // Uncommenting this line will disable assertions
#include <assert.h>
int main() {
int value = 4;
assert(value < 5); // This will pass
return 0;
}
You can create your own custom assertion macros to log error messages specific to your debugging needs. By combining assertions with custom logging, you can better understand the state of your program when an assertion fails.
#include <assert.h>
#include <stdio.h>
#define custom_assert(condition, message) \
do { \
if (!(condition)) { \
fprintf(stderr, "%s:%d: Assertion '%s' failed: %s\n", __FILE__, __LINE__, #condition, message); \
assert(condition); \
} \
} while (0)
int main() {
int number = 3;
custom_assert(number > 5, "Number must be greater than 5!"); // This will trigger the custom assertion
return 0;
}