Menu

#120 Align cases of simple switch statements if there is enough room

1.0
open
nobody
None
2019-07-21
2019-07-21
digory
No

Consider this code snippet:

int f1() {
   switch (value) {
   case 1: return 42;
   case 24455: return 77 + someFun();
   default: return 0;
   }
}

int f2() {
   switch (value) {
   case 1: return 42;
   case 2: return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20;
   default: return 0;
   }
}

int f3() {
   switch (value) {
   case 1:
      return 42;
   case 2:
      return 77 + someFun();
   default:
      return 0;
   }
}

int f4() {
   switch (value) {
   case 1: return 42;
   case 2: int a = 77; return someFun(77);
   default: return 0;
   }
}

With --style=allman --max-code-length=80 --indent-after-parens I currently get:

int f1()
{
    switch (value)
    {
    case 1:
        return 42;
    case 24455:
        return 77 + someFun();
    default:
        return 0;
    }
}

int f2()
{
    switch (value)
    {
    case 1:
        return 42;
    case 2:
        return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17

            + 18 + 19 + 20;
    default:
        return 0;
    }
}

int f3()
{
    switch (value)
    {
    case 1:
        return 42;
    case 2:
        return 77 + someFun();
    default:
        return 0;
    }
}

int f4()
{
    switch (value)
    {
    case 1:
        return 42;
    case 2:
        int a = 77;
        return someFun(77);
    default:
        return 0;
    }
}

What I'd like to see:

int f1()
{
    switch (value)
    {
    case 1:     return 42;
    case 24455: return 77 + someFun();
    default:    return 0;
    }
}

int f2()
{
    switch (value)
    {
    case 1:
        return 42;
    case 2:
        return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17

            + 18 + 19 + 20;
    default:
        return 0;
    }
}

int f3()
{
    switch (value)
    {
    case 1:  return 42;
    case 2:  return 77 + someFun();
    default: return 0;
    }
}

int f4()
{
    switch (value)
    {
    case 1:
        return 42;
    case 2:
        int a = 77;
        return someFun(77);
    default:
        return 0;
    }
}

Explanation:

* The cases of f1 are kept on single lines, because there is enough room. However, the instructions are indented such that all of them align.
* The cases of f2 are broken on multiple lines, because one of the cases do not fit on a single line.
* The cases of f3 are forced on a single line, because there is enough room.
* The cases of f4 are NOT forced on a single line, because one of the cases aren't simple, i.e. there are multiple instructions.

Discussion


Log in to post a comment.

MongoDB Logo MongoDB