How to Add Message to Assert in C++

In C++, assert is a debugging tool that allows the users to test assumptions in their code. The standard assert macro provided by <cassert> checks the condition and if the condition is evaluated as false, the assert statement terminates the program and prints an error message on the console along with the source code file name and the line number. In this article, we will learn how to add a message to assert in C++.

Add Message to Assert in C++

By default, the error message printed by the assert statement is not informative and consists of the source code file name and the line number. The following message is printed by default by the assert:

Assertion failed: condition, file file_name.cpp, line number ...

The default error returned by the assert does not give much context about why the assert got executed or what the expected behavior was. Adding a message to the assert statement can provide more useful debugging information to the user and make it easier to identify and fix bugs. To add a custom message to an assert statement in C++, the following syntax can be followed:

Syntax

#define ASSERT(condition, message) \
do { \
assert(condition && message); \
} while (0)

where:

  • ASSERT: is a macro that takes two arguments condition and message.
  • Condition: is defined as the condition the user wants to check for.
  • Message: is the custom message string that the user wants to return on the console when the assertion is executed.

Note: Inside the macro, built in assert is used that concatenates the condition and the message string using the logical and (&&) operator and the stringizing(#) operator.

C++ Program to Add Message to Assert

The following program illustrates how we can add a custom message to assert in C++:

C++
// C++ Program to Add Message to Assert 
#include<iostream>
#include <cassert>
#include <cstdio>
using namespace std;

//Define the macro for assert
#define ASSERT(condition, message) \
   do { \
      assert(condition && #message); \
   } while (0)


int main() {
   int x = 20;
   int y = 10;
    
   // Adding condition and message to the assert
   ASSERT(x + y == 15, "x + y should be 15");

   cout<<"Program Executed Successfully"<<endl;

   return 0;
}

Output

a.out: main.cpp:16: int main(): Assertion `x + y == 15 && "\"x + y should be 15\""' failed.

Time Complexity: O(1)
Auxiliary Space: O(1)


Contact Us