编程参考 - 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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜流冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值