heh, I was half way through typing this and wondering if it was really that useful, but since Matt and Graeme have both posted answers about this I'll continue.
A few days ago while adding a new case to a switch I forgot to end the case with a break. Once I found the error I changed the indentation of my switch statement from:
switch(var) {
case CONST1:
statement;
statement;
statement;
break;
case CONST2:
statement;
statement;
statement;
case CONST3:
statement;
statement;
break;
default:
statement;
}
(which is how guess most people would normally indent)
to this:
switch(var) {
case CONST1:
statement;
statement;
statement;
break;
case CONST2:
statement;
statement;
statement;
case CONST3:
statement;
statement;
break;
default:
statement;
}
To make the missing break stand out, and to make me more likely not to forget to add one when I'm adding a new case. (of course you can't do this if your breaking conditionally in more than one place, which I've done on occasion)
If I'm only doing something trivial like setting a variable or calling functions from the case statements then I often structure them like this:
switch(var) {
case CONST1: func1(); break;
case CONST2: func2(); break;
case CONST3: func3(); break;
default: statement;
}
That makes it super obvious if you miss a break. If your statements aren't the same length add whitespace till the breaks align, along with anything else that makes sense:
switch(var) {
case CONST1: func1("Wibble", 2); break;
case CONST2: longnamedfunc2("foo" , 3); break;
case CONST3: variable = 2; break;
default: statement;
}
Although if I'm passing the same parameters to each function I would use a function pointer (the following is actual code from a work project):
short (*fnExec) ( long nCmdId
, long * pnEnt
, short vmhDigitise
, short vmhToolpath
, int *pcLines
, char ***prgszNCCode
, map<string, double> *pmpstrd
) = NULL;
switch(nNoun) {
case NOUN_PROBE_FEED: fnExec = &ExecProbeFeed; break;
case NOUN_PROBE_ARC: fnExec = &ExecProbeArc; break;
case NOUN_PROBE_SURFACE: fnExec = &ExecProbeSurface; break;
case NOUN_PROBE_WEB_POCKET: fnExec = &ExecProbeWebPocket; break;
default: ASSERT(FALSE);
}
nRet = (*fnExec)(nCmdId, &nEnt, vmhDigitise, vmhToolpath, &cLines, &rgszNCCode, &mpstrd);