What is the "assert" function?


I've been studying OpenCV tutorials and came across the assert function; what does it do?

6/25/2013 6:51:38 PM

Accepted Answer

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.

// BAD


// Watch out! Depends on the function:

// Here's a safer way:
int ret = foo();

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).

12/10/2017 3:51:29 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow