assert() Function Example in C Programming

In this source code example, we will see how to use the assert() macro in C programming with an example.

assert() Function Overview

The assert() macro is provided in the <assert.h> header of C. It is typically used during the debugging phase of software development to insert diagnostic tests into a program. 

When the expression passed to assert() evaluates to false (0), the program outputs an error message and terminates. This can help identify assumptions made during coding and catch unexpected conditions that violate them. 

Key Points: 

- Requires the <assert.h> header. 

- Accepts an expression. If the expression evaluates to false (0), assert() triggers an error. 

- Is typically used during debugging and can be turned off (made inert) by defining NDEBUG before including <assert.h>

- Terminates the program if the condition is not met, thereby highlighting the failure point.

Source Code Example

#include <stdio.h>
#include <assert.h>  // Required for assert()

int main() {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    // Assuming age can't be negative or over 150 for this example
    assert(age >= 0 && age <= 150);

    printf("Your age is %d.\n", age);

    return 0;
}

Output

Enter your age: 30
Your age is 30.
Or
Enter your age: -5
Assertion failed: (age >= 0 && age <= 150), function main, file source_file.c, line 12.

Explanation

1. The necessary header files, stdio.h for input/output and assert.h for the assert() macro, are included.

2. Inside the main() function, an integer variable age is declared to store the user's input.

3. The user is prompted to input their age.

4. The assert() macro checks whether the age is in the assumed valid range (0 to 150 in this case).

5. If the age is outside this range, assert() triggers an error message and terminates the program.

6. If the age is valid, the program continues and prints out the age.

Using the assert() macro is an effective way to ensure that certain conditions or assumptions made during coding hold true during execution. However, care should be taken to not use it as a substitute for proper error handling, especially in production code.


Comments