What is assert() in C?
In C programming, assert()
is a macro that is used to assist with debugging by checking assumptions made by the program. It is defined in the <assert.h>
header file. The assert()
function tests a given condition (usually expressed as a boolean expression) and if the condition evaluates to false
(0), it prints an error message to the standard error stream (stderr
) and aborts the program execution by calling abort()
. This helps in identifying logical errors and assumptions that fail during runtime, especially during the development phase.
Syntax of assert()
The syntax of assert()
is simple:
assert(expression);
- expression: This is the condition you expect to be true under normal circumstances. If
expression
evaluates tofalse
, the macro reports an error and terminates the program.
Behavior of assert()
When the expression
passed to assert()
evaluates to true (non-zero), the program continues to execute without any interruption. If expression
evaluates to false:
- An error message is printed to
stderr
. This message includes the expression that failed, along with the filename and line number where theassert()
call is located. - The function
abort()
is called, which terminates the program execution.
Example Usage of assert()
Here’s a simple example demonstrating how assert()
can be used in a C program:
#include <assert.h> #include <stdio.h> int main() { int age = 25; // Check the condition that 'age' should be greater than or equal to 18 assert(age >= 18); printf("Age is: %d\n", age); // An example where the assertion will fail age = 15; assert(age >= 18); // This will fail and terminate the program printf("This line will not be printed.\n"); return 0; }
In this example:
- When
age
is 25, theassert()
call does nothing alarming, and the program prints the age. - When
age
is set to 15, theassert(age >= 18)
will fail. An error message will be printed, and the program will terminate before the nextprintf()
statement.
Disabling assert()
The functionality of assert()
can be turned off by defining the macro NDEBUG
before the #include <assert.h>
directive. This is useful for disabling assertion checks in the production version of a program, where you typically don’t want the overhead of checks or program abortion due to failed assertions.
#define NDEBUG #include <assert.h>
With NDEBUG
defined, all calls to assert()
are effectively ignored, and no checks are performed.
Conclusion
The assert()
macro is a powerful tool for debugging during development. It helps ensure that certain conditions are met during program execution, and if not, it provides a clear indication of where and why the program failed. However, remember that assertions are generally disabled in production code, as they can cause the program to terminate abruptly if an assertion fails. Instead, proper error handling should be implemented for production scenarios.
GET YOUR FREE
Coding Questions Catalog