Assertion in C++

In this tutorial, we are going to learn how we can use assertion in our C++ program. Assertions are statements that are assumed to be true. If not true, the compiler throws an error.

assertion in C++

The syntax for an assertion is as follows:

void assert(int exp)

If the expression passed in assert() function is true, then the program execution continues normally. If the expression doesn’t hold true, an error is thrown with the expression statement, filename, and the line number.

The below program explains the working of the assert() function.

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

int main()
{
    int a;
    cout << "Enter a positive number.\n";
    cin >> a;
    assert(a>0);
    cout << "Great! You entered a positive number.";
    
    return 0;
}

The above program takes input from the user. As you can see in the program, we have made an assertion that the given input must be a positive integer. Let’s see how the program behaves for different inputs.

When we enter a positive number as input.

The output will be:

Enter a positive number.
5
Great! You entered a positive number.

Now when we enter a non-positive number as input the compiler throws an error as shown in the below output.

Output:

Enter a positive number.
-3
Assertion failed!

Program: C:\Users\Ranjeet Verma\Documents\assert.exe
File: assert.cpp, Line 10

Expression: a>0

Removing assertion from the program

We can define macro NODEBUG to remove the effect of assertion from our C++ program. Note that we should define NODEBUG before we include <assert.h>. Have a look at the code below.

#define NDEBUG

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

int main()
{
    int a;
    cout << "Enter a positive number.\n";
    cin >> a;
    assert(a>0);
    cout << "Entering non-positive number does not throw any error now.";
    
    return 0;
}

Output:

Enter a positive number.
-6
Entering non-positive number does not throw any error now.

Thank you.

Also, read: Errors in C++

Leave a Reply

Your email address will not be published. Required fields are marked *