Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Switch-case curly braces after every case

In a C switch-case flow control, it's required to put curly braces { } after a case if variables are being defined in that block.

Is it bad practice to put curly braces after every case, regardless of variable declaration?

For example:

switch(i) {   case 1: {     int j = 4;     ...code...   } break;    case 2: {  //No variable being declared! Brace OK?     ...code...   } break; } 
like image 312
Ben Avatar asked Nov 22 '10 01:11

Ben


1 Answers

It's certainly not invalid to use braces in every case block, and it's not necessarily bad style either. If you have some case blocks with braces due to variable declarations, adding braces to the others can make the coding style more consistent.

That being said, it's probably not a good idea to declare variables inside case blocks in straight C. While that might be allowed by your compiler, there's probably a cleaner solution. Mutually-exclusive case blocks may be able to share several common temporary variables, or you may find that your case blocks would work better as helper functions.

like image 178
bta Avatar answered Sep 27 '22 22:09

bta