第 26 / 187 篇

2.9.1. 常量、switch、enum 与 typedef

说明

本文是个人学习用的非官方中英对照译文,原文: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 if statements.

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, and NAME):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <stdlib.h>

#define N (20) // N: alias for the literal value 20
#define PI (3.14) // PI: alias for the literal value 3.14
#define NAME ("Sarita") // NAME: alias for the string literal "Sarita"

int main(void) {
int array[N]; // an array of 20 ints
int *d_arr, i;
double area, circ, radius;

radius = 12.3;
area = PI*radius*radius;
circ = 2*PI*radius;

d_arr = malloc(sizeof(int)*N);
if(d_arr == NULL) {
printf("Sorry, %s, malloc failed!\n", NAME);
exit(1);
}
for(i=0; i < N; i++) {
array[i] = i;
d_arr[i] = i*2;
}
...

使用常量能让代码更易读(在表达式中,PI 比 3.14 更有意义),也让代码更易修改。例如,要改变上面程序中数组的边界和 pi 值的精度,程序员只需修改常量的定义并重新编译;所有用到这些常量的代码都会使用新的值。例如:

Using constants makes the code more readable (in an expression, PI has more meaning than 3.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
2
3
4
5
6
7
8
9
10
11
#define N    (50)        // redefine N from 20 to 50
#define PI (3.14159) // redefine PI to higher precision

int main(void) {
int array[N]; // now allocates an array of size 50
...
area = PI*radius*radius; // now uses 3.14159 for PI
d_arr = malloc(sizeof(int)*N); // now mallocs array of 50 ints
...
for(i=0; i < N; i++) { // now iterates over 50 elements
...

要记住,常量不是左值——它们是 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
2
3
4
5
#define N  20

int main(void) {
...
N = 50; // compilation error: `20 = 50` is not valid C

switch 语句

Switch statements

C 的 switch 语句可以代替某些(但不是全部)串联的 if-else if 代码序列。虽然 switch 并没有为 C 语言增加任何表达能力,但它常常能写出更简洁的分支代码,还可能让编译器生成比等价的串联 if-else if 代码执行得更高效的分支代码。

The C switch statement can be used in place of some, but not all, chaining if-else if code sequences. While switch doesn’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 chaining if-else if code.

switch 语句的 C 语法如下:

The C syntax for a switch statement looks like:

1
2
3
4
5
6
7
8
9
10
11
12
switch (<expression>) {

case <literal value 1>:
<statements>;
break; // breaks out of switch statement body
case <literal value 2>:
<statements>;
break; // breaks out of switch statement body
...
default: // default label is optional
<statements>;
}

switch 语句的执行过程如下:

A switch statement is executed as follows:

  1. 首先对 expression 求值。
  1. The expression evaluates first.
  1. 接着,switch 查找与表达式的值相匹配的 case 字面值。
  1. Next, the switch searches for a case literal value that matches the value of the expression.
  1. 找到匹配的 case 字面值后,就从紧跟其后的语句开始执行。
  1. Upon finding a matching case literal, it begins executing the statements that immediately follow it.
  1. 如果没有找到匹配的 case,并且存在 default 标签,就从 default 标签处的语句开始执行。
  1. If no matching case is found, it will begin executing the statements in the default label if one is present.
  1. 否则,switch 语句体中的语句都不会执行。
  1. Otherwise, no statements in the body of the switch statement get executed.

关于 switch 语句的几条规则:

A few rules about switch statements:

译注 · 两处更准确的说法

  • 下面第一条说 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 case must be a literal value — it cannot be an expression. The original expression gets matched for equality only with the literal values associated with each case.
  • 执行到 break 语句时,switch 语句体中剩余的所有语句都不再执行。也就是说,break 跳出 switch 语句体,从整个 switch 代码块之后的下一条语句继续执行。
  • Reaching a break statement stops the execution of all remaining statements inside the body of the switch statement. That is, break breaks out of the body of the switch statement and continues execution with the next statement after the entire switch block.
  • 值相匹配的 case 语句标记的是将要执行的 C 语句序列的起点——执行会跳到 switch 体内的某个位置开始执行代码。因此,如果某个 case 的末尾没有 break 语句,后续各 case 下的语句会依次执行,直到执行了一条 break 语句或到达 switch 语句体的末尾为止。
  • The case statement with a matching value marks the starting point into the sequence of C statements that will be executed — execution jumps to a location inside the switch body to start executing code. Thus, if there is no break statement at the end of a particular case, then the statements under the subsequent case statements execute in order until either a break statement is executed or the end of the body of the switch statement is reached.
  • default 标签是可选的。如果有,它必须放在最后。
  • The default label is optional. If present, it must be at the end.

下面是一个含 switch 语句的示例程序:

Here’s an example program with a switch statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>

int main(void) {
int num, new_num = 0;

printf("enter a number between 6 and 9: ");
scanf("%d", &num);

switch(num) {
case 6:
new_num = num + 1;
break;
case 7:
new_num = num;
break;
case 8:
new_num = num - 1;
break;
case 9:
new_num = num + 2;
break;
default:
printf("Hey, %d is not between 6 and 9\n", num);
}
printf("num %d new_num %d\n", num, new_num);
return 0;
}

下面是这段代码的几次运行示例:

Here are some example runs of this code:

1
2
3
4
5
6
7
8
9
10
11
12
./a.out
enter a number between 6 and 9: 9
num 9 new_num 11

./a.out
enter a number between 6 and 9: 6
num 6 new_num 7

./a.out
enter a number between 6 and 9: 12
Hey, 12 is not between 6 and 9
num 12 new_num 0

枚举类型

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 (enum is a keyword in C):

1
2
3
4
5
6
enum type_name {
CONST_1_NAME,
CONST_2_NAME,
...
CONST_N_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
2
3
4
5
6
7
enum days_of_week {
MON,
TUES,
WED,
THURS,
FRI
};

枚举类型的变量用类型名 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
2
3
4
5
6
7
enum days_of_week day;

day = THURS;

if (day > WED) {
printf("The weekend is arriving soon!\n");
}

枚举类型类似于用 #define 定义一组常量,如下所示:

An enumerated types is similar to defining a set of constants using #define like the following:

1
2
3
4
5
#define MON    0
#define TUES 1
#define WED 2
#define THURS 3
#define FRI 4

枚举类型中的常量值可以像常量那样使用,让程序更易读、代码更易更新。不过,枚举类型的一个优点是把一组相关的整数常量组织在一起。它还是一种类型定义,所以变量和参数可以声明为枚举类型,而常量只是字面值的别名。此外,枚举类型中各常量的具体值是从 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 #define constant definitions:

1
2
3
4
5
6
7
8
9
enum days_of_week {
SUN, // SUN will now be 0
MON, // MON will now be 1, and so on
TUES,
WED,
THURS,
FRI,
SAT
};

虽然枚举类型中的常量会被隐式赋值,程序员也可以用 = val 语法给它们指定具体的值。例如,如果程序员希望一周各天的值从 1 而不是从 0 开始,可以这样写:

Although values are implicitly assigned to the constants an enumerated type, the programmer can also assign specific values to them using = val syntax. 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
2
3
4
5
6
7
8
9
enum days_of_week {
SUN = 1, // start the sequence at 1
MON, // this is 2 (next value after 1)
TUES, // this is 3, and so on
WED,
THURS,
FRI,
SAT
};

由于枚举类型为一组 int 字面值定义了别名,枚举类型的值打印出来是它的 int 值,而不是别名的名字。例如,按照上面 enum days_of_week 的定义,下面的代码打印的是 3,而不是字符串 "TUES":

Because an enumerated type defines aliases for a set of int literal values, the value of an enumerated type prints out as its int value and not as the name of the alias. For example, given the above definition of the enum days_of_week, the following prints 3 not the string "TUES":

1
2
3
4
enum days_of_week day;

day = TUES;
printf("Today is %d\n", 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 break before the next case statement (when val is FRI two printf statements are executed before a break is encountered, and when val is MON or WED only one of the printf statements is executed before the break):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// an int because we are using scanf to assign its value
int val;

printf("enter a value between %d and %d: ", SUN, SAT);
scanf("%d", &val);

switch (val) {
case FRI:
printf("Orchestra practice today\n");
case MON:
case WED:
printf("PSYCH 101 and CS 231 today\n");
break;
case TUES:
case THURS:
printf("Math 311 and HIST 140 today\n");
break;
case SAT:
printf("Day off!\n");
break;
case SUN:
printf("Do weekly pre-readings\n");
break;
default:
printf("Error: %d is not a valid day\n", val);
};

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 with typedef:

1
typedef existing_type_name new_type_alias_name;

下面是一段使用 typedef 的程序片段:

Here is an example partial program that uses typedefs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#define MAXNAME  (30)
#define MAXCLASS (40)

enum class_year {
FIRST = 1,
SECOND,
JUNIOR,
SENIOR,
POSTGRAD
};

// classYr is an alias for enum class_year
typedef enum class_year classYr;

struct studentT {
char name[MAXNAME];
classYr year; // use classYr type alias for field type
float gpa;
};

// studentT is an alias for struct studentT
typedef struct studentT studentT;

// ull is an alias for unsigned long long
typedef unsigned long long ull;

int main(void) {

// declare variables using typedef type names
studentT class[MAXCLASS];
classYr yr;
ull num;

num = 123456789;
yr = JUNIOR;
strcpy(class[0].name, "Sarita");
class[0].year = SENIOR;
class[0].gpa = 3.75;

...

由于 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 typedef and listing the name of the type alias after the closing } in the struct definition. For example, the following defines both a struct type struct studentT and an alias for the type named studentT:

1
2
3
4
5
typedef struct studentT {
char name[MAXNAME];
classYr year; // use classYr type alias for field type
float gpa;
} studentT;

这个定义与上例中在结构体定义之后单独进行 typedef 是等价的。

This definition is equivalent to doing the typedef separately, after the the struct definition as in the previous example.