Assertion in Computer Programming

In computing, Assertion is a standard debugging tool. Mainly used while the development process of a software application in order to find the critical logic error easily. The functions of assertion work differently language by language. In java programming, the assertion is disabled by default, programmers can enable it anytime in the debug setting for debugging the code.

Languages like C or C++ assertion is completely absent by default. But there is a library called <cassert> in C++ and <assert.h> in C that include only the assert macro. So to use assertion in C/C++ or this kind of language, at first programmers include the assertion library.

Assert Functions

A stated assert function returns the boolean values true (1) or false (0) in a program. When logic is checked by the assert macro, if the logic gets false or impossible, then the assert macro sends the detailed error in the logs.

After then the abort() function is automatically called for exiting the program. An assertion is used for run-time checking instead of compiling a critically crashed program. That means a critical logic that even can not handle the compiler, by using assertion is helpful or minor and major bug tracking.

For example, we may check a variable and compare it to its value using the assertion function. If initially, the comparison returns false the entire program will be broken with the error. If we reassign the compared value to the same variable later, it won’t reach there. Check out the following example in the C program:

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

int main(void) {
    int x = 5; // the value of x is now 5
    assert(x == 9); //the checking position

    //reassigning the value of x to 9
    x = 9;

    /* the program will break at line 6
       because the condition does not meet to true
       Although we reassigned the value 9 to x later
       It happened because of run-time assertion */
}

Output:

Assertion failed!
File: assert.c, line 6
Expression: x == 9

By the way, assert are used in a very complex problem where even compile can’t catch the logical bug. In this case, the assertion can be used as a very powerful debugging tool. Experts and smart programmers often use assertion for complex code debugging.