Re: assert(false) vs abort()
Ulrich Eckhardt <eckhardt@satorlaser.com> wrote:
Greetings!
I have a piece of code like this:
int frobnicate(short foo) {
switch(foo) {
case bar: return 0;
case baz: return 1;
default: assert(false);
}
}
Now, when I compile this, the compiler complains that not every path
returns
a value. Thinking about it, it even makes sense because the 'false' is
only
evaluated at runtime so the compiler can't know that this will terminate
the program.
There is also the fact that the default block wont terminate the problem
in all cases (if NDEBUG is defined, then what does frobnicate() return?)
Okay, I thought, then I'll replace this with a simple abort() call.
Does that remove the compiler's complaint?
However,
there are two things that annoy me there:
1. The call isn't removed with NDEBUG.
That is a good thing. You don't want release code returning some random
value in the default case, that's a bug that can be very hard to track.
2. I don't get the same diagnostic support as assert() gets, like having
the
file/line/function dumped to stderr and a debugger waiting for me there to
inspect the situation.
How do you deal with this situation?
int frobnicate( short foo ) {
assert( foo == bar || foo == baz );
return foo == baz;
}
The cyclomatic complexity has been lowered from 3 to 1, and all possible
paths are covered.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]