Re: assert(false) vs abort()
Daniel T. wrote:
Ulrich Eckhardt <eckhardt@satorlaser.com> wrote:
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?
Yes, the compiler knows that abort() will never return.
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.
My assumption is simply that the default block will never be called. While
debugging, I use the assertion to catch and then fix cases where this
invariant is violated, typically when someone added another value to an
enumeration. Yes I know that it can be really hard to track down this case
when some bug does get through to the released software.
I do admit that I might be optimising prematurely...
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.
Well, this is good and fine as long as we stay in the confines of this
example, but typically the switch blocks have a few more values and the
return value is more than a boolean in the disguise of an integer. ;)
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]