Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert() - what is it good for ?

Tags:

c++

assert

I don't understand the purpose of assert() .

My lecturer says that the purpose of assert is to find bugs .

For example :

double divide(int a , int b ) 
{
  assert (0 != b);
  return a/b;
}

Does the above assert justified ? I think that the answer is yes , because if my program doesn't supposed to work with 0 (the number zero) , but somehow a zero does find its way into the b variable , then something is wrong with the code .

Am I correct ?

Can you show me some examples for a justified assert() ?

Regards

like image 334
JAN Avatar asked Nov 28 '22 02:11

JAN


1 Answers

assert is used to validate things that should always be true if the program is correct. Whether assert is justified in your example depends on the specification of divide: if b != 0 is a precondition, then the assert is usually the preferred way of verifying it: if someone calls the function without fulfilling the preconditions, it is a programming error, and you should terminate the program with extreme prejudice, doing as little additional work as possible. (Usually. There are applications where this is not the case, and where it is better to throw an exception, and stumble along, hoping for the best.) If, however, the specification of divide defines somw behavior when b == 0 (e.g. return +/-Inf), then you should implement this instead of using assert.

Also, it's possible to turn the assert off, if it turns out that it takes too much runtime. Generally, however, this should only be done in critical sections of code, and only if the profiler shows that you really need it.

FWIW: not related to your question, but the code you've posted will return 0.0 for divide( 1, 3 ). Somehow, I don't think that this is what you wanted.

like image 94
James Kanze Avatar answered Dec 08 '22 18:12

James Kanze