AppDividend
Latest Code Tutorials

C++ Assertions Example | Assertions In C++ Tutorial

0

C++ Assertions Example | Assertions In C++ Tutorial is today’s topic. Assertions are statements that are used to explicitly check for logically incorrect conditions in different segments of the code. If the assumption made by the assertion statement is wrong, it shows an error message in the output stream. Assertion statements are generally used after the development of the program, during the debugging part. It helps the programmer to check for the logically incorrect statements which may be syntactically correct.

C++ Assertions

Assertion statements are used too extensively during the debugging period rather than a general error handling statements because of their ease to disable all of them at once. 

Unlike the general error handling statements which are required to be removed explicitly from the code once the error is resolved, the assertion statements can all be disabled at once using just a single macro execution.

Assertions are the statements used to test assumptions made by the programmer. For example, we may use the assertion to check if the pointer returned by malloc() is NULL or not.

If an expression evaluates to 0 (false), then the expression, source code filename, and the line number are sent to a standard error, and then the abort() function is called.

#Header file

If we want to use assertion in C++, we always have to include asser.h header file.

See the following syntax.

void assert(expression);

See the following example.

assert(x/y==45);

(Note that we will use the double equal operator not the single one because we are comparing the two sides of the equation.)

#Program to show usage of Assert statement

See the following program.

#include <iostream>
using namespace std;
#include <assert.h>
int main()
{
    int var1,var2;
    cout<<"Enter two positive numbers"<<endl;
    cin>>var1>>var2;

    /*  Checking if the user has entered positive numbers only */
    assert(var1>0);
    cout<<"First number is positive"<<endl;
    assert(var2>0);
    cout<<"Second number is positive"<<endl;
    return 0;
}

On the above program, we will see that, if we enter any negative number ( see output file) it will pass through an error message.

#Advantages

The various advantages of using Assertion statements include:

It lets you test the edge cases for a particular condition. Using the assertion statement in different portions of the code can help you get the statements where the values of say objects changes and helps to take appropriate steps for it. See the following code example.

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

int main()
{
    int a = 5;

    /*  Code just mistakenly changes the value of a from 5 to let us say 6 */
    a = 6;

    /* Now we can check for the validity of a being 5 till the end of program */
    assert(a == 5);

    return 0;
}

#Output

Assertion failed: a==5, file sample.cpp 
This application has requested the Runtime to terminate it in an unusual way... 

Using the assertion statements, we can show custom error messages in the output stream. Rather than the conventional error handling, we can have a separate error message to be shown for each particular case.

We can disable all the error messages made using the assertion statement at once for the whole program. Rather than the case with normal error handling, where every error case is to be removed explicitly, in case of assertion statement calls, it can be done just by executing a single macro (NDEBUG).

See the following code example.

#include <iostream>
using namespace std;
#define NDEBUG
#include <assert.h>

int main()
{
    int a = 5;

    /*  Code just mistakenly changes the value of a from 5 to let us say 6 */
    a = 6;

    /* Now we can check for the validity of a being 5 till the end of program */
    assert(a == 5);
    cout << "Successful" << endl;

    return 0;
}

See the following output.

Successful

#Disadvantages

The major disadvantage of using the assertion statement for error handling is that they can’t be run during the execution time. The assertion statements are used to check for the possible errors while debugging the code for the final execution.

But during execution, the assertion statements if used gives the error message it is supposed to and then calls the C++ abort function, terminating the program and stopping its execution altogether.

#Assertion Vs. Normal Error Handling

Assertions are mainly used to check a logically impossible situation. For instance, they can be used to check a state the code expects before it starts running or state after it finishes the running.

Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in assert() that can cause side effects. For example, writing something like assert(x = 5) is not a good idea as x is changed, and this change won’t happen when assertions are disabled. See this for more details.

See one more example of assertion in C++.

/* assert example */
#include <stdio.h>  /* printf */
#include <assert.h> /* assert */

void print_number(int *myInt)
{
    assert(myInt != NULL);
    printf("%d\n", *myInt);
}

int main()
{
    int a = 10;
    int *b = NULL;
    int *c = NULL;

    b = &a;

    print_number(b);
    print_number(c);

    return 0;
}

In this example, assert is used to abort a program execution if the print_number is called with a null pointer as an attribute. This happens on a second call to a function, which triggers the assertion failure to signal the bug.

So, here we end the concept of Assertion in C++.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.