1

I prefer this indentation style for switch cases with local variables:

switch (expr) {
case CONST_BLAH1: {
        int decl; // scope local to this case
        stmt;
        break;
case CONST_BLAH2: } {
        stmt;
        break;
case CONST_BLAH3: } {
        int x, y;
        stmt;
        break;
case CONST_BLAH4: }
        // because this is the last case we don't introduce new scope
        int x, y;
        stmt;
}

My current C-indentation options are:

set cinoptions=:0,l1,(s,m1

And Vim indents the code like this:

switch (expr) {
case CONST_BLAH1: {
        int decl;
        stmt;
        break;
case CONST_BLAH2: } {
        stmt;
        break;
case CONST_BLAH3: } {
        int x, y;
        stmt;
        break;
case CONST_BLAH4: } 
                  int x, y;
                  stmt;
}

Why does it align the statements in CONST_BLAH4 to the previous closing }? And how do I remove this behavior?

  • This is a guess, but I believe that before ANSI C (1989) extra scopes inside the function were not allowed (or were proprietary extensions). Original vi is from the late '70s, before ANSI C. But I repeat, this is a guess. – grochmal Jul 29 '16 at 19:35
  • 3
    After a quick search, it looks like scopes are skipped when searching for case in switch statements, which I think is reasonable. Just a guess, but I think the cinoptions parser only sees your first case expression. Why aren't you closing the scope before the next case, anyways? – Tommy A Aug 1 '16 at 17:21
  • @TommyA Closing after the next case is a part of the coding style. Closing before the next case looks confusing when the case labels aren't indented. – wefwefa3 Aug 1 '16 at 18:42
  • 2
    @ryvnf, closing the braces after the case label is quite strange indeed. If in the block of CONST_BLAH3 you do a goto CONST_BLAH1, you would be jumping inside a block that is going to be closed immediately. This would be at best inefficient. I know you are going to say you don't do goto case_label, the point is that this construct is just unnatural. – Shahbaz Aug 7 '16 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.