第 165 / 187 篇

16.3. 条件语句与循环

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix1/conditionals.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

16.3. Conditionals and Loops

表 1 表明,C 和 Java 中 if-else 语句的语法和语义是相同的。

Table 1 shows that the syntax and semantics of if-else statements in C and Java are the same.

表 1. Java 与 C 中 if-else 语句的语法比较

Table 1. Syntax Comparison of if-else Statements in Java and C

Java 版本

Java version

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
/* Java if-else example */

import java.util.Scanner;

class IfExample {

public static void main(String[] args) {

int n1, n2;
Scanner in = new Scanner(System.in);

System.out.print("Enter 1st num: ");
n1 = in.nextInt();
System.out.print("Enter 2nd num: ");
n2 = in.nextInt();

if (n1 > n2) {
System.out.printf("%d is biggest\n",n1);
n2 = n1;
} else {
System.out.printf("%d is biggest\n",n2);
n1 = n2;
}
}

}

C 版本

C version

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
/* C if-else example */

#include <stdio.h>



int main(void) {

int n1, n2;


printf("Enter 1st num: ");
scanf("%d", &n1);
printf("Enter 2nd num: ");
scanf("%d", &n2);

if (n1 > n2) {
printf("%d is biggest\n",n1);
n2 = n1;
} else {
printf("%d is biggest\n",n2);
n1 = n2;
}

return 0;
}

Java 和 C 中 if-else 语句的语法完全相同。在两种语言中,else 部分都是可选的。Java 和 C 也都支持通过串接 if 和 else if 语句来实现多路分支。下面是完整的 C if-else 语法:

The Java and C syntax for if-else statements is identical. In both, the else part is optional. Java and C also support multi-way branching by chaining if and else if statements. The following describes the full if-else C syntax:

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
// a one-way branch:
if ( <boolean expression> ) {
<true body>
}

// a two-way branch:
if ( <boolean expression> ) {
<true body>
}
else {
<false body>
}

// a multibranch (chaining if-else if-...-else)
// (has one or more 'else if' following the first if):
if ( <boolean expression 1> ) {
<true body>
}
else if ( <boolean expression 2> ) {
// first expression is false, second is true
<true 2 body>
}
else if ( <boolean expression 3> ) {
// first and second expressions are false, third is true
<true 3 body>
}
// ... more else if's ...
else if ( <boolean expression N> ) {
// first N-1 expressions are false, Nth is true
<true N body>
}
else { // the final else part is optional
// if all previous expressions are false
<false body>
}

16.3.1. C 中的布尔值

16.3.1. Boolean Values in C

C 没有提供取值为 true 或 false 的布尔类型。取而代之的是,整数值在条件语句中会被当作真(true)或假(false)来求值。在条件表达式中,任何整数表达式:

C doesn’t provide a Boolean type with true or false values. Instead, integer values evaluate to true or false when used in conditional statements. When used in conditional expressions, any integer expression that is:

现代更新(截至 2026-11)· C 早已有布尔类型

原书说「C 没有提供布尔类型」,这只对 C89 成立。从 C99 起,C 有内置类型 _Bool,包含 <stdbool.h> 后可以写作 bool、true、false;到了 C23,bool、true、false 直接成为语言关键字,无需包含头文件。条件语句中「0 为假、非 0 为真」的规则不变。cppreference:Boolean type support · cppreference:C23

  • 为零(0)时求值为假
  • zero (0) evaluates to false
  • 为非零(任何正值或负值)时求值为真
  • nonzero (any positive or negative value) evaluates to true

C 有一组用于布尔表达式的关系运算符和逻辑运算符,它们与 Java 的关系运算符和逻辑运算符完全相同。

C has a set of relational and logical operators for Boolean expressions that are identical to Java’s relational and logical operators.

关系运算符(relational operator)的操作数类型相同,求值结果为零(假)或非零(真)。关系运算符包括:

The relational operators take operand(s) of the same type and evaluate to zero (false) or nonzero (true). The set of relational operators are:

  • 相等(==)和不等(!=)
  • equality (==) and inequality (not equal, !=)
  • 比较运算符:小于(<)、小于等于(<=)、大于(>)和大于等于(>=)
  • comparison operators: less than (<), less than or equal (<=), greater than (>), and greater than or equal (>=)

下面是几段展示关系运算符用法的 C 代码片段:

Here are some C code snippets showing examples of relational operators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// assume x and y are ints, and have been assigned
// values before this point in the code

if (y < 0) {
printf("y is negative\n");
} else if (y != 0) {
printf("y is positive\n");
} else {
printf("y is zero\n");
}

// set x and y to the larger of the two values
if (x >= y) {
y = x;
} else {
x = y;
}

C 的逻辑运算符(logical operator)以整数形式的「布尔」值为操作数,求值结果为零(假)或非零(真)。逻辑运算符包括:

C’s logical operators take integer “Boolean” operand(s) and evaluate to either zero (false) or nonzero (true). The set of logical operators are:

  • 逻辑非(!)
  • logical negation (!)
  • 逻辑与(&&):遇到第一个为假的表达式就停止求值(短路求值)
  • logical and (&&): stops evaluating at the first false expression (short-circuiting)
  • 逻辑或(||):遇到第一个为真的表达式就停止求值(短路求值)
  • logical or (||): stops evaluating at the first true expression (short-circuiting)

C 的逻辑运算符采用短路(short-circuit)求值:一旦逻辑表达式的结果已经确定,就停止求值。例如,如果逻辑与(&&)表达式的第一个操作数为假,那么整个 && 表达式的结果必然为假。因此第二个操作数的值无需求值,也确实不会被求值。

C’s short-circuit logical operator evaluation stops evaluating a logical expression as soon as the result is known. For example, if the first operand to a logical and (&&) expression evaluates to false, the result of the && expression must be false. As a result, the second operand’s value need not be evaluated, and it is not evaluated.

下面是一个在 C 条件语句中使用逻辑运算符的例子(对于复杂的布尔表达式,最好总是加上括号,使其更易读):

The following is an example of conditional statements in C that use logical operators (it’s always best to use parentheses around complex Boolean expressions to make them easier to read):

1
2
3
4
5
6
7
8
9
if ( (x > 10) && (y >= x) ) {
printf("y and x are both larger than 10\n");
x = 13;
} else if ( ((-x) == 10) || (y > x) ) {
printf("y might be bigger than x\n");
x = y * x;
} else {
printf("I have no idea what the relationship between x and y is\n");
}

16.3.2. C 中的循环

16.3.2. Loops in C

Java 和 C 都在语言层面支持重复执行一段代码。与 Java 一样,C 支持 for、while 和 do-while 循环。这些循环在两种语言中的语法和语义完全相同。Java 还支持对集合进行迭代,而 C 没有这种功能。

Java and C both have language-level support for repeating a sequence of code. Like Java, C supports for, while, and do-while loops. The syntax and semantics of these are identical in both languages. Java additionally has support for iterating over collections that C does not have.

while 循环

while Loops

C 和 Java 中的 while 循环语法完全相同,行为也一样。表 2 展示了一个带 while 循环的 C 示例程序。

The while loop syntax in C and Java is identical, and the behavior is the same. Table 2 shows an example C program with a while loop.

表 2. C 中的 while 循环语法

Table 2. while Loop Syntax in C

C 的 while 循环示例

C while loop example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* C while loop example */

#include <stdio.h>

int main(void) {

int num, val;

printf("Enter a value: ");
scanf("%d", &num);
// make sure num is not negative
if (num < 0) {
num = -num;
}
val = 1;
while (val < num) {
printf("%d\n", val);
val = val * 2;
}

return 0;
}

C 中的 while 循环语法与 Java 中的相同,两者的求值方式也一样:

The while loop syntax in C is the same as in Java and both are evaluated in the same way:

1
2
3
while ( <boolean expression> ) {
<true body>
}

while 循环先检查布尔表达式,如果为真就执行循环体。在前面的示例程序中,val 变量的值会在 while 循环中被反复打印,直到它的值大于 num 变量的值为止。如果用户输入 10,C 和 Java 程序都会打印:

The while loop checks the Boolean expression first and executes the body if true. In the preceding example program, the value of the val variable will be repeatedly printed in the while loop until its value is greater than the value of the num variable. If the user enters 10, the C and Java programs will print:

1
2
3
4
1
2
4
8

Java 和 C 也都有 do-while 循环,它与 while 循环类似,但先执行循环体,再检查条件,只要条件为真就重复执行循环体。也就是说,do-while 循环总会至少执行一次循环体:

Java and C also has a do-while loop that is similar to its while loop, but it executes the loop body first and then checks a condition and repeats executing the loop body for as long as the condition is true. That is, a do-while loop will always execute the loop body at least one time:

1
2
3
do {
<body>
} while ( <boolean expression> );

想看更多 while 循环的例子,可以试试下面两个程序:

For additional while loop examples, try these two programs:

for 循环

for Loops

C 中的 for 循环与 Java 中的 for 循环相同,求值方式也一样。C(和 Java)的 for 循环语法是:

The for loop in C is the same as the for loop in Java, and they are evaluated in the same way. The C (and Java) for loop syntax is:

1
2
3
for ( <initialization>; <boolean expression>; <step> ) {
<body>
}

for 循环的求值规则是:

The for loop evaluation rules are:

  1. 第一次进入循环时,对初始化部分求值一次。
  1. Evaluate initialization one time when first entering the loop.
  1. 对布尔表达式求值。如果它为 0(假),就跳出 for 循环(即程序不再重复执行循环体语句)。
  1. Evaluate the boolean expression. If it’s 0 (false), drop out of the for loop (that is, the program is done repeating the loop body statements).
  1. 执行循环体中的语句。
  1. Evaluate the statements inside the loop body.
  1. 对步进(step)表达式求值。
  1. Evaluate the step expression.
  1. 从第(2)步开始重复。
  1. Repeat from step (2).

下面是一个打印 0、1、2 的简单 for 循环示例:

Here’s a simple example for loop to print the values 0, 1, and 2:

1
2
3
4
5
int i;

for (i = 0; i < 3; i++) {
printf("%d\n", i);
}

对上面的循环套用 for 循环的求值规则,会得到如下的动作序列:

Executing the for loop evaluation rules on the preceding loop yields the following sequence of actions:

1
2
3
4
5
6
7
8
9
10
11
(1) eval init: i is set to 0  (i=0)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (0)
(4) eval step: i is set to 1 (i++)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (1)
(4) eval step: i is set to 2 (i++)
(2) eval bool expr: i < 3 is true
(3) execute loop body: print the value of i (2)
(4) eval step: i is set to 3 (i++)
(2) eval bool expr: i < 3 is false, drop out of the for loop

下面的程序展示了一个更复杂的 for 循环例子(也可以下载)。注意,C 虽然支持在 for 循环的初始化和步进部分写一串语句,但最好还是保持简单(这个例子展示了一种更复杂的 for 循环语法,但如果把它简化,把步进语句 j += 10 移到循环体的末尾,只保留一条步进语句 i += 1,这个 for 循环会更容易阅读和理解)。

The following program shows a more complicated for loop example (it’s also available to download). Note that just because C supports for loops with a list of statements for its initialization and step parts, it’s best to keep it simple (this example illustrates a more complicated for loop syntax, but the for loop would be easier to read and understand if it were simplified by moving the j += 10 step statement to the end of the loop body and having just a single step statement, i += 1).

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 example of a more complex for loop which uses multiple variables.
* (it is unusual to have for loops with multiple statements in the
* init and step parts, but C supports it and there are times when it
* is useful...don't go nuts with this just because you can)
*/
#include <stdio.h>

int main(void) {
int i, j;

for (i=0, j=0; i < 10; i+=1, j+=10) {
printf("i+j = %d\n", i+j);
}

return 0;
}

// the rules for evaluating a for loop are the same no matter how
// simple or complex each part is:
// (1) evaluate the initialization statements once on the first
// evaluation of the for loop: i=0 and j=0
// (2) evaluate the boolean condition: i < 10
// if false (when i is 10), drop out of the for loop
// (3) execute the statements inside the for loop body: printf
// (4) evaluate the step statements: i += 1, j += 10
// (5) repeat, starting at step (2)

与 Java 一样,在 C 中,for 循环和 while 循环的表达能力是相同的,即任何 while 循环都可以表示为 for 循环,反之亦然。

As in Java, in C for loops and while loops are equivalent in power, meaning that any while loop can be expressed as a for loop, and vice versa.

来看下面这个 C 中的 while 循环:

Consider the following while loop in C:

1
2
3
4
5
6
7
int guess = 0;

while (guess != num) {
printf("%d is not the right number\n", guess);
printf("Enter another guess: ");
scanf("%d", &guess);
}

这个循环可以翻译成 C 中等价的 for 循环:

This loop can be translated to an equivalent for loop in C:

1
2
3
4
5
6
7
int guess;

for (guess = 0; guess != num; ) {
printf("%d is not the right number\n", guess);
printf("Enter another guess: ");
scanf("%d", &guess);
}

由于在 C 中 for 循环和 while 循环的表达能力相同,语言中其实只需要一种循环结构。然而,for 循环更适合表达确定次数的循环(例如遍历一个范围内的值),而 while 循环更适合表达不确定次数的循环(例如一直重复,直到用户输入一个偶数为止)。因此,C(和 Java)把两者都提供给程序员。

Because for and while loops are equally expressive in C, only one looping construct is needed in the language. However, for loops are a more natural language construct for definite loops (like iterating over a range of values), whereas while loops are a more natural language construct for indefinite loops (like repeating until the user enters an even number). As a result, C (and Java) provides both to programmers.