What is the "assert" function? What is the "assert" function? c c

What is the "assert" function?


assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.

For example:

assert(length >= 0);  // die if length is negative.

You can also add a more informative message to be displayed if it fails like so:

assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");

Or else like this:

assert(("Length can't possibly be negative! Tell jsmith", length >= 0));

When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert statements by defining the NDEBUG macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.

// BADassert(x++);// GOODassert(x);    x++;// Watch out! Depends on the function:assert(foo());// Here's a safer way:int ret = foo();assert(ret);

From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).


The assert computer statement is analogous to the statement make sure in English.


Take a look at

assert() example program in C++

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.

Eg

#include <stdio.h>#include <assert.h>void analyze (char *, int);int main(void){   char *string = "ABC";   int length = 3;   analyze(string, length);   printf("The string %s is not null or empty, "          "and has length %d \n", string, length);}void analyze(char *string, int length){   assert(string != NULL);     /* cannot be NULL */   assert(*string != '\0');    /* cannot be empty */   assert(length > 0);         /* must be positive */}/****************  Output should be similar to  ******************The string ABC is not null or empty, and has length 3