编程参考 - Switch Case Range in GNU C Extensions

Extensions to the C Language Family

Case Ranges (Using the GNU Compiler Collection (GCC))

6.32 Case Ranges

You can specify a range of consecutive values in a single case label, like this:

case low ... high:

This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive.

This feature is especially useful for ranges of ASCII character codes:

case 'A' ... 'Z':

Be careful: Write spaces around the ..., for otherwise it may be parsed wrong when you use it with integer values. For example, write this:

case 1 ... 5:

rather than this:

case 1...5:

The values in case labels must reduce to integer constants. They can use arithmetic, and enum constants, but they cannot refer to data in memory, because they have to be computed at compile time. It is an error if two case labels specify the same value, or ranges that overlap, or if one is a range and the other is a value in that range.

You can also define a default case to handle “any other value,” like this:

default:
    statements
    break;

If the switch statement has no default: label, then it does nothing when the value matches none of the cases.

The brace-group inside the switch statement is a block, and you can declare variables with that scope just as in any other block (see Blocks). However, initializers in these declarations won’t necessarily be executed every time the switch statement runs, so it is best to avoid giving them initializers.

break; inside a switch statement exits immediately from the switch statement.

If there is no break; at the end of the code for a case, execution continues into the code for the following case. This happens more often by mistake than intentionally, but since this feature is used in real code, we cannot eliminate it.

Warning: When one case is intended to fall through to the next, write a comment like ‘falls through’ to say it’s intentional. That way, other programmers won’t assume it was an error and “fix” it erroneously.

Consecutive case statements could, pedantically, be considered an instance of falling through, but we don’t consider or treat them that way because they won’t confuse anyone.

参考:

Case Ranges (Using the GNU Compiler Collection (GCC))

你可能感兴趣的:(编程参考,gnu)