Answer: ‘assert()’ is a macro therefore it doesn’t have a prototype. Yet, we can give following illustration to better understand this.
int assert(int expression);
‘assert()’ is useful to test expression argument that ought to be true. If it happens to be false, it displays a massage on stderr and terminates the program. If, on the other hand, expression found to be true, it does nothing. Therefore, this macro makes debugging easier because as soon as assertion isn’t true, macro terminates the program and displays error massage. Format of error massage is implementation defined. For example,
/* assert.c -- program does assertions */ #include <stdio.h> 1503 <div style="text-align:justify"> #include <stdlib.h> #include <assert.h> /* macro assert() declared */ int main(void) { FILE *fp; fp = fopen("hello.txt", "r"); /* let's assert if file opened successfully */ assert(fp != NULL); /* do processing here */ /* close file */ fclose(fp); return 0; }
Notice the output of the above program given as below
a.out: assert.c:14: main: Assertion `fp != ((void *)0)' failed. Aborted (core dumped)
Notice that error massage includes executable file name (a.out), program file name (assert.c), line no (14), function in which assert macro called (main) and assertion with status.
You can sprinkle ‘assert()’ macro throughout the program to debug the it. Notice, however, that it’s not appropriate for handling situations like, test whether input is valid and if it’s not, request user to re-enter the correct input because it terminates the program.
Once, program is thoroughly tested, eliminate assertions either by adding ‘#define NDEBUG’ macro prior to ‘assert.h’ header or by compiling the program with ‘-DNDEBUG’ command-line option. For example,
/* assert.c -- program does assertions */ #include <stdio.h> #include <stdlib.h> #define NDEBUG /* Macro NDEBUG included prior to assert.h */ #include <assert.h> /* macro assert() declared */
Effect of using ‘#define NDEBUG’ causes the preprocessor to discard the assertions and thereby eliminating ours’ overhead of having to phsically delete them.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Practice Computer Science MCQs
- Check Computer Science Books