Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date