assert() example program in C++

By: Charles Emailed: 1643 times Printed: 2109 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Rather than depending on the compiler-provided assert(), you are free to write your own assert() macro. Listing below provides a simple assert() macro and shows its use.

A simple assert() macro.

1:     //ASSERTS
2:     #define DEBUG
3:     #include <iostream.h>
5:     #ifndef DEBUG
6:        #define ASSERT(x)
7:     #else
8:        #define ASSERT(x) \
9:                 if (! (x)) \
10:                { \
11:                   cout << "ERROR!! Assert " << #x << " failed\n"; \
12:                   cout << " on line " << __LINE__  << "\n"; \
13:                   cout << " in file " << __FILE__ << "\n";  \
14:                }
15:    #endif
18:    int main()
19:    {
20:       int x = 5;
21:       cout << "First assert: \n";
22:       ASSERT(x==5);
23:       cout << "\nSecond assert: \n";
24:       ASSERT(x != 5);
25:       cout << "\nDone.\n";
26:     return 0;
27: }

Output: First assert:

Second assert:
ERROR!! Assert x !=5 failed
 on line 24
 in file test1704.cpp

Analysis: On line 2, the term DEBUG is defined. Typically, this would be done from the command line (or the IDE) at compile time, so you can turn this on and off at will. On lines 8-14, the assert() macro is defined. Typically, this would be done in a header file, and that header (ASSERT.HPP) would be included in all your implementation files.

On line 5, the term DEBUG is tested. If it is not defined, assert() is defined to create no code at all. If DEBUG is defined, the functionality defined on lines 8-14 is applied.

The assert() itself is one long statement, split across seven source code lines, as far as the precompiler is concerned. On line 9, the value passed in as a parameter is tested; if it evaluates FALSE, the statements on lines 11-13 are invoked, printing an error message. If the value passed in evaluates TRUE, no action is taken.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

Thanks a lot!!!.Quite helpful article.
keep this good thing going
I think the explanation could be simplified by keeping the verbage down a bit(Please review and act).

View Tutorial          By: Raj at 2008-03-14 03:59:56
2. View Comment

it's cool
but on other way it is indeed hard and exciting...

View Tutorial          By: johncarlo at 2009-02-05 04:44:13
3. View Comment


View Tutorial          By: Anon at 2009-02-12 07:51:44
4. View Comment

Splendid! Haven\'t used asserts before, very helpful

View Tutorial          By: Anonymous at 2009-03-11 04:18:42
5. View Comment

thanks a lot ..

View Tutorial          By: indra at 2009-03-25 15:40:03
6. View Comment

Thank you

View Tutorial          By: dara at 2009-12-19 02:46:52
7. View Comment

it should be:
/* --------------- */
#define ASSERT(x)
if (x) {} \
else { \
//.. bla bla bla
/* ---------------- */

Gues what happen if u use ur version like that:
if (x < 3)
ASSERT(x >= 0);


View Tutorial          By: Ryba at 2010-05-19 15:45:48
8. View Comment

thank you

View Tutorial          By: cutiegurl at 2011-01-18 20:23:39
9. View Comment

Thank You

View Tutorial          By: Alex at 2011-02-09 04:26:07
10. View Comment

Protip: you could add some inline assembly with the following code:

int 3

This calls interrupt 3, which is a breakpoint. Causing your debugger to break at that spot. How inline assembly works depends on your compiler

View Tutorial          By: Robin Degen at 2011-08-16 23:47:04

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Dot (.) vs Arrow (->) to access data members in C++
Difference between Procedural, Structured, and Object-Oriented Programming
The if Statement in C++
Use of Conditional (Ternary) Operator in C++
Converting C++ Abstract Classes into Java Interfaces
atoi(), itoa() in C++
assert() example program in C++
Using cout.width() in C++
virtual inheritance example in C++
Implementing Pure Virtual Functions in C++
Enumerations in C++
Compute the square root of the sum of the squares of an array in C++
A Brief History of C++
C++ and Object-Oriented Programming
Getting Started with C++
Most Emailed Articles (in C++)
Returning values from a function in C++
while (1) Loops in C++
Using Comments in a C++ Program
Specifying default values to function parameters in C++
continue and break statements in C++
The indirection operator (*) - dereference operator.
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
How to use Enumerated constants in C++
Advanced if Statements in C++
while Loops in C++
Converting Pointer Parameters in C++ to Java
assert() Versus Exceptions in C++
Compute the square root of the sum of the squares of an array in C++
A Brief History of C++