Add custom messages in assert in C++

Hello Friends, In this tutorial, we will look at how to add custom messages in assert in C++. To get an idea of assert please check here Assertion in C++.

Let’s see the basic structure of assert:

void assert(expression)

It takes conditional expressions as input and assumes it to be true. If these are true it executes normally otherwise it terminates and displays an error with expression statement, filename, and the line number that it occurred in.

We will make use of the idea that strings are evaluated to true if used as a condition.

if("hello")
{
   cout<<"true";
}

Output:

true

We know that if we have two conditions, condition1 and condition2 then if we take Logical OR of ( condition1 || condition2) it results in true if at least one of them is true and if we take Logical AND of ( condition1 && condition2 ) it results in true only if both of them is true otherwise it results in false.

So, we will add our message with the expression(that has to be checked) using && operator as our message being a condition2 will be evaluated to true always and the whole expression’s bool value inside assert will depend on the condition1 bool value only.

Modified Syntax to be used for adding a message is:

void assert(exp && message)

The below program explains the working of the idea that is used in assert() function.

#include <iostream>
#include <assert.h>
using namespace std;
int main()
{
    int x=5;
    
    assert(x==6 && "x is not equal to 6");
    cout<<"x is 6";
   
    
    return 0;
}

Output:

a.out: assert.cpp:8: int main(): Assertion `x==6 && "x is not equal to 6"' failed.
Aborted (core dumped)

In the above program, variable x is assigned a value of 5 and it is not equal to 6 so condition1(x==6) becomes false and the whole expression value becomes false and the compiler throws an error with the line number it has occurred in.

If we set the value of variable x to 6 then we get our output as:

x is 6

as condition1(x==6) is true and condition2(Our message) is true.

Thank You

Leave a Reply

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