Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Using the Assert Macro

Question:
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?

Answer:
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) 
  exit(-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.

 

 

Sitemap