Reputation: 35
Just out of curiosity, I was wondering why the indentantation on switch statements are the way they are. I'd expect that break; should be written on the same column as case: like we do with curly brackets on an if statement.
So why do we do it like this:
case 1:
//do stuff
break;
case 2:
case 3:
//do stuff
break;
And not like this:
case 1:
//do stuff
break;
case 2:
case 3:
//do stuff
break;
Upvotes: 1
Views: 174
Reputation: 66
There is no difference in either of those two ways of writing switch statements. If I wanted I could also write a switch statement like this
case 1: /*do stuff*/ break;case 3: case 2: /*do stuff*/ break;
The whitespaces you add will not be read by the compiler. We add the spaces and the indentation so as to make our code easily readable to others.
In 4 words: no blocks, no indentation.
Cases are not opening a block. In C or C++ you can even put variables declarations (but the initializers are not called, except for static variables, that's a pitfall) at the beginning of the switch block.
Hence, as cases are just labels, indenting them does not seem that intuitive, and not indenting is the style chosen by most styles.
Upvotes: 1
Reputation: 1358
IMHO, the first example is more clear, you can see each case without barriers. The second example is more difficult because in the same level there are case and break and you can't divide blocks so easy.
Upvotes: 0