Assertions in C/C++

An assertion in C is a debugging tool that checks if a condition is true during program execution. When an assertion fails, the program displays an error message and terminates immediately. This helps catch programming errors early in the development process.

In C programming, assertions are implemented using the assert() macro defined in the <assert.h> header file. The macro evaluates an expression and aborts the program if the expression is false.

Syntax

#include <assert.h>
assert(expression);

Parameters:

  • expression − A condition that should be true. If it evaluates to false (0), the program terminates with an error message.

When to Use Assertions

Assertions are useful in the following scenarios −

  • To check conditions that should never occur in a correctly written program
  • To validate function parameters and preconditions
  • To catch logical errors during development and testing
  • To document assumptions made in the code

Example 1: Basic Assertion Usage

This example demonstrates basic assertion usage to validate conditions that must be true −

#include <assert.h>
#include <stdio.h>

int main() {
    int number = 15;
    char message[] = "Hello World";
    
    // Assert that number is positive
    assert(number > 0);
    printf("Number is positive: %d\n", number);
    
    // Assert that string is not empty
    assert(message[0] != '\0');
    printf("Message: %s\n", message);
    
    printf("All assertions passed!\n");
    return 0;
}
Number is positive: 15
Message: Hello World
All assertions passed!

Example 2: Assertion Failure

This example shows what happens when an assertion fails −

#include <assert.h>
#include <stdio.h>

int divide(int a, int b) {
    assert(b != 0);  // Ensure divisor is not zero
    return a / b;
}

int main() {
    int result;
    
    // This will work fine
    result = divide(10, 2);
    printf("10 / 2 = %d\n", result);
    
    // This will cause assertion failure
    result = divide(10, 0);
    printf("10 / 0 = %d\n", result);  // This line won't execute
    
    return 0;
}
10 / 2 = 5
main.c:6: divide: Assertion `b != 0' failed.
Aborted

Key Points

  • Assertions are only active in debug builds. They can be disabled by defining NDEBUG before including <assert.h>
  • When an assertion fails, the program prints the filename, line number, and the failed condition
  • Assertions should not be used for handling expected runtime errors or user input validation
  • They are primarily for catching programming logic errors during development

Conclusion

Assertions in C are powerful debugging tools that help validate program assumptions and catch errors early. They should be used to check conditions that must always be true in correct programs, making code more reliable and easier to debug.

Updated on: 2026-03-15T10:16:00+05:30

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements