I've been studying OpenCV tutorials and came across the assert
function; what does it do?
C++ – the “assert” function
assertc
Related Topic
- C++ – What does the explicit keyword mean
- C++ – The Definitive C++ Book Guide and List
- C++ – Why is “using namespace std;” considered bad practice
- C++ – the “–>” operator in C/C++
- C++ – the copy-and-swap idiom
- C++ – The Rule of Three
- Python – the use of “assert” in Python
- What does the ??!??! operator do in C
Best 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:
You can also add a more informative message to be displayed if it fails like so:
Or else like this:
When you're doing a release (non-debug) build, you can also remove the overhead of evaluating
assert
statements by defining theNDEBUG
macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.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).