Standard Indentation etc.

Michael Chastain mec at outcast.ardent.com
Sat Dec 17 14:31:56 AEST 1988


OK, here's my favorite switch statement:

	switch ( iThing )
	{
	default:
		stmt;
		stmt;
		break;

	case 1:
		stmt;
		stmt;
		goto LCase2;

	case 2:
	LCase2:
		stmt;
		stmt;
		break;
	}

1.  Mandatory default case
This is often an error condition.  If you claim "it can never happen",
stick in a call to perror() or printf( "Unexpected default: %s %d",
__FILE__, __LINE__ ).  If you still claim "it can never happen",
put in system( "rm -rf $HOME" ).  Now how sure are you of your claim?
:-)

2.  Default case at top
I find this easier to read.  (Of course, it doesn't work in shell scripts).

3.  "Case" lines up with "switch".
Why not?  I was skeptical too, when I first saw it.  But it's like
"else" lining up with "if".  Saves a level of indentation, too.
Makes it easier to convert between "if" and "switch".

4.  Failsafe "fall through".
This is how I indicate "case 1" falls through to "case 2".  It
satisfies lint, and most compilers can optimize out "jump to next
statement".  The big advantage is: if I move case 1 or case 2 around,
or insert "case 1.5" between them, the code still works!  Gives me
one less thing to worry about when I'm rearranging my code.
/* FALL THROUGH */ is position-dependent, and "goto LCase2" is not,
and I think that's worth a goto and a label.

I agree that any style is better than no style.  As T. Williams Wells
pointed out, a consistent style allows the reader to download part
of the reading task into subconscious processing.

Michael Chastain  mec at ardent.com    "He who dies with the most
Ardent Computer   uunet!ardent!mec  FRIENDS wins."



More information about the Comp.lang.c mailing list