Reputation: 1217
Preface: This question is not a duplicate of this one:
This question is also not opinion-based. I am not seeking the "best" style. I am not asking what is the "right" thing to do.
What I am asking is how different coding styles indent switch statements, their case labels, and the actual statements.
I'm particularly interested in how a switch statement is indented in
- K&R style
- Linux kernel style
- GNU style
- Java style
My idea is to be able to be consistent in whatever code I am working with, but most indent style examples don't have switch cases. I like consistency, and the idea that what I'm writing doesn't actually match what I'm writing to is tolerable, but untasty.
Upvotes: 8
Views: 4252
Reputation: 11237
From his book (pg. 59):
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
ndigit[c-'0']++;
break;
case ' ':
case '\n':
case '\t':
nwhite++;
break;
default:
nother++;
break;
}
A little inconsistent with the fall-throughs, but otherwise visible coding style.
Upvotes: 0
Reputation: 1217
Since the question is collecting downvotes like rainwater, I decided to find where the hell each style came from and what they said on the matter. Feel free to add. (I don't have a copy of K&R, or Whitesmiths, for example)
Java style
Specified by Oracle
www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
Specifies a comment for whenever break
is omitted.
Linux Kernel style
Used in the Linux Kernel - I hope
https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/tree/kernel/kcov.c?h=v4.15.8
switch (size) {
case 8:
type |= KCOV_CMP_SIZE(0);
break;
case 16:
type |= KCOV_CMP_SIZE(1);
break;
case 32:
type |= KCOV_CMP_SIZE(2);
break;
case 64:
type |= KCOV_CMP_SIZE(3);
break;
default:
return;
}
I couldn't find an example for fallthroughs.
GNU style
There's a book.
https://www.gnu.org/prep/standards/standards.html
Says nothing. Looked up GNU-Emacs instead, at the suggestion of Wikipedia.
https://github.com/emacs-mirror/emacs/blob/master/src/cm.c
switch (use)
{
case USEHOME:
statement;
break;
case USELL:
statement;
break;
case USECR:
statement;
break;
}
next statement;
Again, no fallthrough. As it is: in...ter...esting...
Upvotes: 4