[Nfd-dev] code-style: switch with compound statement

Junxiao Shi shijunxiao at email.arizona.edu
Wed Aug 12 07:13:39 PDT 2015


Dear folks

rule 1.10 gives two forms for switch statements. The preferred form is:

switch (cond) {
case 1:
  stmts;
  // Fallthrough

case 2:
  stmts;
  break;

default:
  stmts;
  break;
}

In reality, ‘stmts;’ may need to declare variables, but declarations are disallowed directly under a ‘case’ label.
The solution is to use a compound statement { stmts; } , inside which declarations can be used.

My question is, how to properly indent a switch statement in which some ‘case’ labels have compound statements?

I prefer the following form:

// option A
switch (cond) {
case 1: {
  int i = 1;
  doSomething(i);
} // Fallthrough

case 2:
  doSomething(2);
  break;

case 3: {
  int j = 3;
  doSomething(j);
} break;

default:
  doSomething(0);
  break;
}

I have also seen:

// option B
switch (cond) {
case 1:
  {
    int i = 1;
    doSomething(i);
  }
  // Fallthrough

case 2:
  doSomething(2);
  break;

case 3:
  {
    int j = 3;
    doSomething(j);
  }
  break;

default:
  doSomething(0);
  break;
}

// option C
switch (cond) {
case 1:
  {
    int i = 1;
    doSomething(i);
    // Fallthrough
  }

case 2:
  doSomething(2);
  break;

case 3:
  {
    int j = 3;
    doSomething(j);
    break;
  }

default:
  doSomething(0);
  break;
}

// option D
switch (cond) {
case 1:
{
  int i = 1;
  doSomething(i);
  // Fallthrough
}

case 2:
  doSomething(2);
  break;

case 2:
{
  int j = 3;
  doSomething(j);
  break;
}

default:
  doSomething(0);
  break;
}

Option B exactly matches rule 1.10 because a compound statement, by definition, is a statement. However, it’s less readable than option A because the actual statements under a ‘case’ label with a compound statement is indented more than the statements under a ‘case’ label without a compound statement.
Option C has the same problem as option B, and also has hides ‘break’ or ‘// Fallthrough’ inside the compound statement making them less visible.
Option D looks okay but in case the last ‘case’ or ‘default’ label contains a compound statement, two ‘}’ would be indented at the same level at the bottom, which is confusing.

What do others on the mailing list think about this?
I intend to amend rule 1.10 when a consensus is reached.

Yours, Junxiao
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.lists.cs.ucla.edu/pipermail/nfd-dev/attachments/20150812/c0b8ce4d/attachment.html>


More information about the Nfd-dev mailing list