Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement formatting

I've been conflicted over how to format switch statements for awhile now. I see three viable options, and while I've been using the first more often than not (As it's the form I see most often), I find the second and third to be more intuitive.

First:

switch(x) {
    case 1:
        DoSomething();
        break;
    case 2:
        DoSomething();
        break;
}

Second:

switch(x) {
    case 1: DoSomething();
        break;
    case 2: DoSomething();
        break;
}

Third:

switch(x) {
    case 1: DoSomething(); break;
    case 2: DoSomething(); break;
}

I understand a lot of code style is preferential, so I'll set my official question as:

Is there anything fundamentally wrong with using the second or third options, so long as it's consistent throughout the code?

like image 580
Cereal Avatar asked Dec 08 '22 13:12

Cereal


1 Answers

As per Oracle Docs;

A switch statement should have the following form:

switch (condition) {
case ABC:
    statements;
    /* falls through */
case DEF:
    statements;
    break;
case XYZ:
    statements;
    break;
default:
    statements;
    break;
}

The important thing here, is to be consistent, when you follow a format.

Hope this helps.

like image 173
JNL Avatar answered Jan 12 '23 00:01

JNL