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:
switch( x )
{
case 0:
printf("Case 0\n");
goto shared_material;
case 1:
printf("Case 1\n");
goto shared_material; // Unnecessary, but keep it for clarity.
case 2:
shared_material:
printf("Case 2\n");
break;
default:
// Write a meaningful error message somewhere
return -1;
}
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.
Why not put the common code after the switch?
I feel I have to update this reply, paraphrasing the accepted answer with one I feel has a better design:
switch( x )
{
case 0:
printf("Case 0\n");
break;
case 1:
printf("Case 1\n");
break;
case 2:
break;
default:
return -1;
}
printf("Common code for cases 0, 1 and 2\n");
Or, you could of course set a flag in the 'default' case that would prevent the common code from executing, if you for some reason don't want to break it out to a separate function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With