说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/advanced_switch.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
2.9.1. Constants, switch, enum, and typedef
常量、switch 语句、枚举类型和 typedef 是 C 语言中有助于写出更易读、更易维护的代码的特性。常量、枚举类型和 typedef 用来在程序中为字面值和类型定义别名。switch 语句可以用来代替某些串联的 if-else if 语句。
Constants, switch statements, enumerated types, and typedef are features of the C language that are useful for creating more readable code and maintainable code. Constants, enumerated types, and typedefs are used to define aliases for literal values and types in programs. Switch statements can be used in place of some chaining
if-else ifstatements.
C 常量
C Constants
常量(constant)是 C 字面值的别名。用常量代替字面值,可以让代码更易读、更易修改。在 C 中,常量在函数体之外用如下语法定义:
A constant is an alias for a C literal value. Constants are used in place of the literal value to make code more readable and easier to modify. In C, constants are defined outside of a function body using the following syntax:
译注
严格地说,#define 定义的是预处理器的宏(macro):编译之前,预处理器会把代码中的宏名原样替换成后面的文本,所以它其实可以写在文件的任何位置(只要在使用之前)。宏值外面加括号是个好习惯,可以避免替换后与周围的运算符结合出错。除了宏,C 中还可以用 const 变量和 enum 常量表示常量;C23 还新增了 constexpr。
1 | #define const_name (literal_value) |
下面是一段定义并使用三个常量(N、PI 和 NAME)的程序片段:
Here is an example of a partial program that defines and uses three constants (
N,PI, andNAME):
1 | #include <stdio.h> |
使用常量能让代码更易读(在表达式中,PI 比 3.14 更有意义),也让代码更易修改。例如,要改变上面程序中数组的边界和 pi 值的精度,程序员只需修改常量的定义并重新编译;所有用到这些常量的代码都会使用新的值。例如:
Using constants makes the code more readable (in an expression,
PIhas more meaning than3.14). Using constants also makes code easier to modify. For example, to change the bounds of the arrays and the precision of the value of pi in the above program, the programmer only needs to change their constant definitions and recompile; all the code that uses the constant will use their new values. For example:
1 | #define N (50) // redefine N from 20 to 50 |
要记住,常量不是左值——它们是 C 类型字面值的别名。因此,它们的值不能像变量那样在运行时改变。例如,下面的代码会导致编译错误:
It is important to remember that constants are not lvalues—they are aliases for literal values of C types. As a result, their values cannot be changed at runtime like those of variables. The following code, for example, causes a compilation error:
1 | #define N 20 |
switch 语句
Switch statements
C 的 switch 语句可以代替某些(但不是全部)串联的 if-else if 代码序列。虽然 switch 并没有为 C 语言增加任何表达能力,但它常常能写出更简洁的分支代码,还可能让编译器生成比等价的串联 if-else if 代码执行得更高效的分支代码。
The C
switchstatement can be used in place of some, but not all, chainingif-else ifcode sequences. Whileswitchdoesn’t provide any additional expressive power to the C programming language, it often yields more concise code branching sequences. It may also allow the compiler to produce branching code that executes more efficiently than equivalent chainingif-else ifcode.
switch 语句的 C 语法如下:
The C syntax for a
switchstatement looks like:
1 | switch (<expression>) { |
switch 语句的执行过程如下:
A switch statement is executed as follows:
- 首先对
expression求值。
- The
expressionevaluates first.
- 接着,
switch查找与表达式的值相匹配的case字面值。
- Next, the
switchsearches for acaseliteral value that matches the value of the expression.
- 找到匹配的
case字面值后,就从紧跟其后的语句开始执行。
- Upon finding a matching
caseliteral, it begins executing the statements that immediately follow it.
- 如果没有找到匹配的
case,并且存在default标签,就从default标签处的语句开始执行。
- If no matching
caseis found, it will begin executing the statements in thedefaultlabel if one is present.
- 否则,
switch语句体中的语句都不会执行。
- Otherwise, no statements in the body of the
switchstatement get executed.
关于 switch 语句的几条规则:
A few rules about
switchstatements:
译注 · 两处更准确的说法
- 下面第一条说
case后面必须是字面值、不能是表达式,这说得太严了:C 标准要求的是整型常量表达式,即编译时就能算出的整数值。所以case 'A':、case N:(N是#define宏)、case MON:(枚举常量)乃至case BASE + 2:都是合法的;不合法的是含变量、要到运行时才能算出的表达式。 - 最后一条说
default标签「如果有,必须放在最后」,这也不对:default可以出现在switch体中的任何位置,放在最后只是惯例。
译者用 gcc -std=c99 -pedantic -Wall 编译了一个把 default 放在最前、case 写成 BASE + 2 和枚举常量的 switch,没有任何警告,运行结果也正确。
- 每个
case关联的值必须是字面值——它不能是表达式。原表达式只与各个case关联的字面值进行相等匹配。
- The value associated with each
casemust be a literal value — it cannot be an expression. The original expression gets matched for equality only with the literal values associated with eachcase.
- 执行到
break语句时,switch语句体中剩余的所有语句都不再执行。也就是说,break跳出switch语句体,从整个switch代码块之后的下一条语句继续执行。
- Reaching a
breakstatement stops the execution of all remaining statements inside the body of theswitchstatement. That is,breakbreaks out of the body of theswitchstatement and continues execution with the next statement after the entireswitchblock.
- 值相匹配的
case语句标记的是将要执行的 C 语句序列的起点——执行会跳到switch体内的某个位置开始执行代码。因此,如果某个case的末尾没有break语句,后续各case下的语句会依次执行,直到执行了一条break语句或到达switch语句体的末尾为止。
- The
casestatement with a matching value marks the starting point into the sequence of C statements that will be executed — execution jumps to a location inside theswitchbody to start executing code. Thus, if there is nobreakstatement at the end of a particularcase, then the statements under the subsequentcasestatements execute in order until either abreakstatement is executed or the end of the body of theswitchstatement is reached.
default标签是可选的。如果有,它必须放在最后。
- The
defaultlabel is optional. If present, it must be at the end.
下面是一个含 switch 语句的示例程序:
Here’s an example program with a
switchstatement:
1 | #include <stdio.h> |
下面是这段代码的几次运行示例:
Here are some example runs of this code:
1 | ./a.out |
枚举类型
Enumerated Types
枚举类型(enumerated type,enum)是定义一组相关整数常量的一种方式。switch 语句和枚举类型常常一起使用。
An enumerated type (
enum) is a way to define a group of related integer constants. Often switch statements and enumerated types are used together.
枚举类型应当在函数体之外定义,语法如下(enum 是 C 的关键字):
The enumerated type should be defined outside of a function body, using the following syntax (
enumis a keyword in C):
1 | enum type_name { |
注意,常量字段由一个以逗号分隔的名字列表指定,并没有显式地给出值。默认情况下,列表中的第一个常量被赋值为 0,第二个为 1,依此类推。
Note that the constant fields are specified by a comma separated list of names and are not explicitly given values. By default, the first constant in the list is assigned the value 0, the second the value 1, and so on.
下面是一个为一周中的各天定义枚举类型的例子:
Below is an example of defining an enumerated type for the days of the week:
1 | enum days_of_week { |
枚举类型的变量用类型名 enum type_name 来声明,它所定义的常量值可以用在表达式中。例如:
A variable of an enumerated type value is declared using the type name
enum type_name, and the constant values it defines can be used in expressions. For example:
1 | enum days_of_week day; |
枚举类型类似于用 #define 定义一组常量,如下所示:
An enumerated types is similar to defining a set of constants using
#definelike the following:
1 | #define MON 0 |
枚举类型中的常量值可以像常量那样使用,让程序更易读、代码更易更新。不过,枚举类型的一个优点是把一组相关的整数常量组织在一起。它还是一种类型定义,所以变量和参数可以声明为枚举类型,而常量只是字面值的别名。此外,枚举类型中各常量的具体值是从 0 开始依次隐式赋予的,程序员不必逐个指定。
The constant values in the enumerated type can be used in a similar way as constants are used to make a program easier to read and code easier to update. However, an enumerated type has an advantage of grouping together a set of related integer constants together. It also is a type definition so variables and parameters can be declared to be an enumerated type, whereas constants are aliases for literal values. In addition, in enumerated types the specific values of each constant is implicitly assigned in sequence starting at
0, so the programmer doesn’t have to specify each constant’s value.
枚举类型的另一个好处是,可以很容易地向集合中添加或删除常量,而不必修改所有常量的值。例如,如果用户想把星期六和星期日加入这组日子,同时保持各天的相对顺序,只需把它们加到枚举类型定义中,而不必像用 #define 定义常量那样显式地重新定义其他常量的值:
Another nice feature of enumerated types is that it is easy to add or remove constants from the set without having to change all their values. For example, if the user wanted to add Saturday and Sunday to the set of days and maintain the relative ordering of the days, they can add them to the enumerated type definition without having to explicitly redefine the values of the others as they would need to do with
#defineconstant definitions:
1 | enum days_of_week { |
虽然枚举类型中的常量会被隐式赋值,程序员也可以用 = val 语法给它们指定具体的值。例如,如果程序员希望一周各天的值从 1 而不是从 0 开始,可以这样写:
Although values are implicitly assigned to the constants an enumerated type, the programmer can also assign specific values to them using
= valsyntax. For example, if the programmer wanted the values of the days of the week to start at 1 instead of 0, they could do the following:
1 | enum days_of_week { |
由于枚举类型为一组 int 字面值定义了别名,枚举类型的值打印出来是它的 int 值,而不是别名的名字。例如,按照上面 enum days_of_week 的定义,下面的代码打印的是 3,而不是字符串 "TUES":
Because an enumerated type defines aliases for a set of
intliteral values, the value of an enumerated type prints out as itsintvalue and not as the name of the alias. For example, given the above definition of theenum days_of_week, the following prints3not the string"TUES":
1 | enum days_of_week day; |
枚举类型常常与 switch 语句结合使用,如下面的示例代码所示。这个例子还展示了一个多个 case 共用同一组语句的 switch 语句,以及一个在下一个 case 语句之前没有 break 的 case 语句(当 val 为 FRI 时,在遇到 break 之前会执行两条 printf 语句;当 val 为 MON 或 WED 时,在 break 之前只执行其中一条 printf 语句):
Enumerated types are often used in combination with switch statements as shown in the example code below. The example also shows a switch statement with several cases associated with the same set of statements, and a case statement that does not have a
breakbefore the next case statement (whenvalisFRItwoprintfstatements are executed before abreakis encountered, and whenvalisMONorWEDonly one of theprintfstatements is executed before thebreak):
1 | // an int because we are using scanf to assign its value |
typedef
typedef
C 提供了用关键字 typedef 定义新类型的方式,新类型是某个已有类型的别名。定义之后,就可以用这个新的类型别名声明变量。这一特性常用来让程序更易读,并使用更短的类型名,常用于结构体和枚举类型。用 typedef 定义新类型的格式如下:
C provides a way to define a new type that is an alias for an existing type using the keyword
typedef. Once defined, variables can be declared using this new alias for the type. This feature is commonly used to make the program more readable and to use shorter type names, often for structs and enumerated types. The following is the format for defining a new type withtypedef:
1 | typedef existing_type_name new_type_alias_name; |
下面是一段使用 typedef 的程序片段:
Here is an example partial program that uses typedefs:
1 | #define MAXNAME (30) |
由于 typedef 常与结构体一起使用,C 提供了把 typedef 与结构体定义合二为一的语法:在结构体定义前加上 typedef,并在结构体定义的右花括号 } 之后写出类型别名。例如,下面的代码既定义了结构体类型 struct studentT,又定义了该类型的别名 studentT:
Because typedef is often used with structs, C provides syntax for combining a typedef and a struct definition together by prefixing the struct definition with
typedefand listing the name of the type alias after the closing}in the struct definition. For example, the following defines both a struct typestruct studentTand an alias for the type namedstudentT:
1 | typedef struct studentT { |
这个定义与上例中在结构体定义之后单独进行 typedef 是等价的。
This definition is equivalent to doing the typedef separately, after the the struct definition as in the previous example.