Original Post
I usually use assert macros to validate my data at the beginning of a function. I was thinking about this situation. The asserts get turned off in a release build, so I am basically assuming that they will never fail (after being tested for a good while in debug mode), and they are only there to help find bugs more easily when I compile in debug mode.
My question is, if I am already assuming that the asserts will never fail, then why not just put in an if-statement and leave it active in release code? My thinking here is that since it can be assumed that the asserts will never fail, the branch prediction will have no problem at all predicting the correct branch in the corresponding if-statement, so there is basically zero overhead involved (assuming the asserts were simple, as in the examples below), and even though the asserts should never fail, it would be nice for the code to do something besides halt the program in the rare event that an assert would have failed.
Here is an example. Normally I might do something like this.
int SomeFunction (int number)
{
assert(number >= 0); // <-- arbitrary asserts
assert(number <= 9);
// code here...
}
I am considering replacing that with something like this.
int SomeFunction (int number)
{
if ((number >= 0) && (number <= 9))
{
// code here...
}
else
{
// report error, return a special value, or whatever
}
}
The first function looks a little cleaner to me, but I can think of situations in my code where I have used asserts, and even though the asserts never fail, there is a reasonable alternative to halting the program in the event that the asserts did fail. Maybe I am just using asserts where I should be using if-statements or exceptions. What is the correct way to handle this?