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.