Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Mar 19, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using the Assert Macro

I am not sure if it is good when I use the assert macro in the following code:
int sum(int number)
// Precondition:  number => 1
// Postcondition: return sum from 1 to n terms
   assert(number >= 1);
   int total = 0;

   for (;number >= 1; number--)
      total = total + number;
   return total;
What do you think?

Using the assert() macro to detect a runtime error is a bad idea; assert() is meant to serve as a debugging aid rather than handling runtime errors. The problem is this: when you build your application as a release version, every occurrence of assert() will be automatically removed from the code (thanks to macro magic). Consequently, your condition will never be tested.

Instead of assert(), you can use a simple IF statement, such as the following:

if (number >= 1) 
Alternatively, you may use exceptions to handle more complicate situations or if your application contains objects that need to be destructed properly before exiting.
DevX Pro
Thanks for your registration, follow us on our social networks to keep up-to-date