assert() Function Example program in C

By: Jagan Emailed: 1588 times Printed: 2039 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

The macro assert() can diagnose program bugs. It is defined in ASSERT.H, and its prototype is

void assert(int expression);

The argument expression can be anything you want to test--a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr and aborts program execution.

How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement

assert(interest_rate >= 0);

at locations in the program where interest_rate is used. If the variable ever does become negative, the assert() macro alerts you. You can then examine the relevant code to locate the cause of the problem.

To see how assert() works, run the sample program below. If you enter a nonzero value, the program displays the value and terminates normally. If you enter zero, the assert() macro forces abnormal program termination. The exact error message you see will depend on your compiler, but here's a typical example:

Assertion failed: x, file list19_3.c, line 13

Note that, in order for assert() to work, your program must be compiled in debug mode. Refer to your compiler documentation for information on enabling debug mode (as explained in a moment). When you later compile the final version in release mode, the assert() macros are disabled.

Using the assert() macro.

1: /* The assert() macro. */
2:
3: #include <stdio.h>
4: #include <assert.h>
5:
6: main()
7: {
8:     int x;
9:
10:     printf("\nEnter an integer value: ");
11:     scanf("%d", &x);
12:
13:     assert(x >= 0);
14:
15:     printf("You entered %d.\n", x);
16:     return(0);
17: }
Enter an integer value: 10
You entered 10.
Enter an integer value: -1
Assertion failed: x, file list19_3.c, line 13
Abnormal program termination

Your error message might differ, depending on your system and compiler, but the general idea is the same.

ANALYSIS: Run this program to see that the error message displayed by assert() on line 13 includes the expression whose test failed, the name of the file, and the line number where the assert() is located.

The action of assert() depends on another macro named NDEBUG (which stands for "no debugging"). If the macro NDEBUG isn't defined (the default), assert() is active. If NDEBUG is defined, assert() is turned off and has no effect. If you placed assert() in various program locations to help with debugging and then solved the problem, you can define NDEBUG to turn assert() off. This is much easier than going through the program and removing the assert() statements (only to discover later that you want to use them again). To define the macro NDEBUG, use the #define directive. You can demonstrate this by adding the line

#define NDEBUG

to Listing above, on line 2. Now the program prints the value entered and then terminates normally, even if you enter -1.

Note that NDEBUG doesn't need to be defined as anything in particular, as long as it's included in a #define directive.


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

Comments(21)


1. View Comment

Nice article..

View Tutorial          By: senthil at 2009-09-09 00:22:40
2. View Comment

awesome. thanks for the info

View Tutorial          By: Darren at 2010-05-09 19:55:22
3. View Comment

"If you enter zero, the assert() macro forces abnormal program termination."

It's not true, please fix.

This is the code:
assert(x >= 0);

assert will be triggered ONLY with negative value.


View Tutorial          By: czx at 2010-09-17 07:23:20
4. View Comment

very usefull article............ thanks to the author... got cleared wit things

View Tutorial          By: runa at 2010-10-16 08:43:38
5. View Comment

Very nice article.... explained the concept very nicely.

View Tutorial          By: prashant yeole at 2010-12-16 03:15:07
6. View Comment

Thanks for this article.

View Tutorial          By: Arindam Dey at 2011-06-16 05:23:17
7. View Comment

Awesome Explanation...:-)

View Tutorial          By: satz at 2011-06-28 01:45:56
8. View Comment

Hi Its very useful ad nice article Thanks

View Tutorial          By: Hanish at 2011-07-22 13:12:23
9. View Comment

thanks nice article , but there is bug as already comment by the CZX . if you enter the 0 then there is no abnornal termination. program will terminate abnormally only for NEGATIVE VALUES

View Tutorial          By: YZ at 2011-08-05 13:10:49
10. View Comment

Thanks for a nice article !!!

View Tutorial          By: Piyush Sharma at 2011-12-15 12:24:06
11. View Comment

simple and clear..

View Tutorial          By: sudhesh at 2011-12-22 04:05:14
12. View Comment

Hi Jgan,
Its very useful ad nice article .
Thanks!!!!!!!


View Tutorial          By: pramod at 2012-01-16 13:21:35
13. View Comment

Thanks ... nice one with clear picture.

View Tutorial          By: Nithin at 2012-04-01 06:58:41
14. View Comment

Thanks Jagan!!!!!!

View Tutorial          By: Maahe at 2012-07-06 05:23:51
15. View Comment

Good one.........!!!

View Tutorial          By: Shailesh Nakade at 2012-07-11 09:48:33
16. View Comment

thnx...nice article...useful..

View Tutorial          By: anish at 2012-11-30 05:41:47
17. View Comment

Really awesome keep posting ........

View Tutorial          By: viswanath at 2013-01-30 07:38:13
18. View Comment

Thanks...Really nice...

View Tutorial          By: Raj at 2013-02-07 08:58:28
19. View Comment

I can't compile the source with Dev-C++ 4.9.9.2, here is the error message:
D:\AP\C\assert.c: In function `main':
D:\AP\C\assert.c:13: error: syntax error at '#' token
D:\AP\C\assert.c:13: warning: passing arg 1 of `_assert' makes pointer from integer without a cast

Execution terminated
Any body explain it, please ....


View Tutorial          By: ToKha at 2013-11-19 01:32:34
20. View Comment

This example is very useful....Thanks for your shared details

View Tutorial          By: raji at 2015-05-22 07:19:07
21. View Comment

Its very usefull to clear understanding for us .Thanks for your update by vijay

View Tutorial          By: vijay at 2015-07-16 09:29:40

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Jagan
Importing a Certificate for the CA example using keytool in Java
The if-then-else Statement in Java
WHERE Clauses in SQL
The TryCatchFinally Interface in JSP
assert() Function Example program in C
Guidelines for Struts Application Development
Using printf function in C
File Inclusion in C
Using Multiple Message Resource Bundles in Struts
While and For Loops in C
Arrays sample program in C
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Using cout.fill() in C++
Types of Profiles in J2ME
DateField sample program in J2ME

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Find square and square root for a given number in C
Using memset(), memcpy(), and memmove() in C
UNIX read and write system calls sample program in C
Open, Creat, Close, Unlink system calls sample program in C
lseek() sample program in C
Formatting with printf in C
Printing a simple histogram in C
Initialization of Variables in C
Listing Files and Directories sample program in C
Sum of the elements of an array in C
perror() Function - example program in C
assert() Function Example program in C
Conditional Expressions in C
Macro Substitution using #define in C
A Storage Allocator sample program in C
Most Emailed Articles (in C)
Open, Creat, Close, Unlink system calls sample program in C
The C Character Set
Using malloc() Function in C
perror() Function - example program in C
Simple arithmetic calculations in C
Increment and Decrement Operators in C
register Variables in C
Bitwise Logical Operators in C
Using qsort() and bsearch() with strings - example program in C
Formatting with printf in C
Printing a simple histogram in C
Relational and Logical Operators in C
While and For Loops in C
goto and labels in C
getch and ungetch in C