Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!ames!ubvax!ardent!outcast!mec From: mec@outcast.ardent.com (Michael Chastain) Newsgroups: comp.lang.c Subject: Re: Standard Indentation etc. Summary: How I write a switch statement Keywords: switch default goto flame bait Message-ID: <952@ardent.UUCP> Date: 17 Dec 88 04:31:56 GMT References: <663@htsa.uucp> <832@husc6.harvard.edu> <22249@apple.Apple.COM> <5358@boulder.Colorado.EDU> Sender: news@ardent.UUCP Reply-To: mec@outcast.ardent.com (Michael Chastain) Organization: Ardent Computer, Sunnyvale, CA Lines: 51 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@ardent.com "He who dies with the most Ardent Computer uunet!ardent!mec FRIENDS wins."