views:

59

answers:

4

Hi!

I was reading through some code (C, if it makes a difference to anyone) today and got curious about a switch-block.

switch (c_type) {
case -1:
    some_function(some_var);
    break;
[...]
default:
    abort();
}

Now, this is a perfectly simple switch-block. It's the some_function(some_var)-call I'm curious about: If you, the programmer, is absolutely, positively, super duper sure that the call will result in the process exiting, do you still put the break-statement underneath even though it is completely unnecessary? Would you say that it is best-practice?

+8  A: 

I would say best practice would be to have a bomb-out assert() below the function call. This serves a dual purpose: it documents the fact that this point in the runtime should be unreachable, and it produces an error message if the code somehow does reach that spot.

Borealid
I was going to say the same as Mark, but this is actually a much better response.
Brendan Long
That's a really good suggestion!
manneorama
+2  A: 

Leave the break in there. It doesn't matter what you are sure about: you write your programs for other humans to read, and the break makes it clear that the given case is completely separate from the case that follows.

Even though you could be absolutely certain about the code today, the specification may change tomorrow and some_function won't exit anymore. Nothing in specifications is certain (in my experience anyway).

Mark Rushakoff
Wish I could give +4 for the "other humans" part.
Bill K
A: 

It's always best practice to end every case statement with a break or return, unless you want it to fall through to the next.

jer
+2  A: 

If I'm super-duper-super-sure that the call would result in the process exiting, I'd stick an assert in just for that.

That way, if someone modifies the function and it doesn't always-terminate, the bug will be caught pretty much the first time it occurs.

EDIT: Beaten, with pretty much the same answer too :/

Anon.