I could use something like javas finally clause in a C switch. Most of my cases has a shared set of functionality that I would like to put a single case. I was thinking of implementing this using goto statements, being well aware of gotos code obfuscation ability, putting the shared case at the bottom of the switch statement still seems a “cleaner” way to do this than partitioning the shared functionality into a seperate function.
Anyway, I have been trying to do it something like this:
switch( x ) {
case 0:
printf("Case 0\n");
goto case 2;
break;
case 1:
printf("Case 1\n");
goto case 2;
break;
case 2:
printf("Case 2\n");
break;
default:
// do nothing
break;
}
However, using gcc, this fail with the error
error: expected identifier or ‘*’ before ‘case’
Any suggestions on how to make it work? Or possibly a better approach?
The “best practice” is of course to delegate the shared code to a function. But in some situations where this is overengineering, or simply not possible / desirable, then you can do:
I don’t find this too unreadable, and I don’t have any problem with it, provided the whole statement fits in one screen (otherwise it qualifies as spaghetti code). However, you may have to defend it in code reviews, which is one of the main reasons I would step away from such constructs and rethink the code.