说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C1-C_intro/conditionals.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
1.3. Conditionals and Loops
表 1 表明,C 和 Python 中 if-else 语句的语法和语义非常相似。主要的语法区别在于:Python 用缩进表示「语句体」,而 C 用花括号(但你在 C 代码中仍然应该保持良好的缩进)。
Table 1 shows that the syntax and semantics of
if-elsestatements in C and Python are very similar. The main syntactic difference is that Python uses indentation to indicate “body” statements, whereas C uses curly braces (but you should still use good indentation in your C code).
表 1. Python 与 C 的 if-else 语句语法对比
Table 1. Syntax Comparison of if-else Statements in Python and C
Python 版本
Python version
1 | # Python if-else example |
C 版本
C version
1 | /* C if-else example */ |
Python 和 C 的 if-else 语句语法几乎一样,只有细微差别。两者的 else 部分都是可选的。Python 和 C 也都支持用 if 和 else if 串联起来实现多路分支。下面是完整的 C if-else 语法:
The Python and C syntax for
if-elsestatements is almost identical with only minor differences. In both, theelsepart is optional. Python and C also support multiway branching by chainingifandelse ifstatements. The following describes the fullif-elseC syntax:
1 | // a one-way branch: |
1.3.1. C 中的布尔值
1.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 为布尔表达式提供了一组关系运算符和逻辑运算符。
C has a set of relational and logical operators for Boolean expressions.
关系运算符(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 | // assume x and y are ints, and have been assigned |
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 | if ( (x > 10) && (y >= x) ) { |
1.3.2. C 中的循环
1.3.2. Loops in C
和 Python 一样,C 支持 for 循环和 while 循环。此外,C 还提供了 do-while 循环。
Like Python, C supports
forandwhileloops. Additionally, C providesdo-whileloops.
while 循环
while Loops
C 和 Python 的 while 循环语法几乎一样,行为也相同。表 2 给出了 C 和 Python 中 while 循环的示例程序。
The
whileloop syntax in C and Python is almost identical, and the behavior is the same. Table 2 shows example programs ofwhileloops in C and Python.
表 2. Python 与 C 的 while 循环语法对比
Table 2. while Loop Syntax Comparison in Python and C
Python 版本
Python version
1 | # Python while loop example |
C 版本
C version
1 | /* C while loop example */ |
C 中的 while 循环语法与 Python 非常相似,两者的求值方式也相同:
The
whileloop syntax in C is very similar in Python, and both are evaluated in the same way:
1 | while ( <boolean expression> ) { |
while 循环先检查布尔表达式,为真时执行循环体。在上面的示例程序中,val 变量的值会在 while 循环中被反复打印,直到它的值大于 num 变量的值为止。如果用户输入 10,C 和 Python 程序都会打印:
The
whileloop checks the Boolean expression first and executes the body if true. In the preceding example program, the value of thevalvariable will be repeatedly printed in thewhileloop until its value is greater than the value of thenumvariable. If the user enters10, the C and Python programs will print:
1 | 1 |
C 还有一种 do-while 循环,它与 while 循环类似,但先执行循环体,再检查条件,只要条件为真就重复执行循环体。也就是说,do-while 循环至少会执行一次循环体:
C also has a
do-whileloop that is similar to itswhileloop, 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, ado-whileloop will always execute the loop body at least one time:
1 | do { |
想看更多 while 循环的例子,可以试试下面两个程序:
For additional
whileloop examples, try these two programs:
for 循环
for Loops
C 中的 for 循环与 Python 中的不同。在 Python 中,for 循环是对序列的迭代;而在 C 中,for 循环是更通用的循环结构。表 3 给出了用 for 循环打印 0 到用户输入的数之间所有值的示例程序:
The
forloop is different in C than it is in Python. In Python,forloops are iterations over sequences, whereas in C,forloops are more general looping constructs. Table 3 shows example programs that useforloops to print all the values between 0 and a user-provided input number:
表 3. Python 与 C 的 for 循环语法对比
Table 3. for Loop Syntax Comparison in Python and C
Python 版本
Python version
1 | # Python for loop example |
C 版本
C version
1 | /* C for loop example */ |
从这个例子可以看出,C 的 for 循环语法与 Python 的 for 循环语法差别很大,求值方式也不同。
In this example, you can see that the C
forloop syntax is quite different from the Pythonforloop syntax. It’s also evaluated differently.
C 的 for 循环语法是:
The C
forloop syntax is:
1 | for ( <initialization>; <boolean expression>; <step> ) { |
for 循环的求值规则是:
The
forloop evaluation rules are:
- 第一次进入循环时,对初始化部分求值一次。
- Evaluate initialization one time when first entering the loop.
- 对布尔表达式求值。如果它为 0(假),就跳出
for循环(即程序不再重复执行循环体语句)。
- Evaluate the boolean expression. If it’s 0 (false), drop out of the
forloop (that is, the program is done repeating the loop body statements).
- 执行循环体中的语句。
- Evaluate the statements inside the loop body.
- 对步进(step)表达式求值。
- Evaluate the step expression.
- 从第(2)步开始重复。
- Repeat from step (2).
下面是一个打印 0、1、2 的简单 for 循环示例:
Here’s a simple example
forloop to print the values 0, 1, and 2:
1 | int i; |
对上面的循环套用 for 循环的求值规则,会得到如下的动作序列:
Executing the
forloop evaluation rules on the preceding loop yields the following sequence of actions:
1 | (1) eval init: i is set to 0 (i=0) |
下面的程序展示了一个更复杂的 for 循环例子(也可以下载)。注意,C 虽然支持在 for 循环的初始化和步进部分写一串语句,但最好保持简单(这个例子演示了较复杂的 for 循环语法;如果把 j += 10 这条步进语句移到循环体末尾,只保留一条步进语句 i += 1,这个 for 循环会更易读、更易懂)。
The following program shows a more complicated
forloop example (it’s also available to download). Note that just because C supportsforloops with a list of statements for its initialization and step parts, it’s best to keep it simple (this example illustrates a more complicatedforloop syntax, but theforloop would be easier to read and understand if it were simplified by moving thej += 10step statement to the end of the loop body and having just a single step statement,i += 1).
1 | /* An example of a more complex for loop which uses multiple variables. |
在 C 中,for 循环和 while 循环的表达能力是等价的,也就是说,任何 while 循环都可以写成 for 循环,反之亦然。Python 则不然:Python 的 for 循环是对一系列值的迭代,因此无法表达某些更通用的 Python while 循环能表达的循环行为。不定次数的循环就是一个例子,在 Python 中只能用 while 循环来写。
In C,
forloops andwhileloops are equivalent in power, meaning that anywhileloop can be expressed as aforloop, and vice versa. The same is not true in Python, whereforloops are iterations over a sequence of values. As such, they cannot express some looping behavior that the more general Pythonwhileloop can express. Indefinite loops are one example that can only be written as awhileloop in Python.
来看下面这个 C 中的 while 循环:
Consider the following
whileloop in C:
1 | int guess = 0; |
这个循环可以翻译成 C 中等价的 for 循环:
This loop can be translated to an equivalent
forloop in C:
1 | int guess; |
而在 Python 中,这种循环行为只能用 while 循环来表达。
In Python, however, this type of looping behavior can be expressed only by using a
whileloop.
由于 C 的 for 循环和 while 循环表达能力相同,语言中其实只需要一种循环结构。不过,for 循环更适合确定次数的循环(比如遍历一个范围内的值),while 循环更适合不定次数的循环(比如一直重复,直到用户输入一个偶数)。因此,C 两种都提供给了程序员。
Because
forandwhileloops are equally expressive in C, only one looping construct is needed in the language. However,forloops are a more natural language construct for definite loops (like iterating over a range of values), whereaswhileloops are a more natural language construct for indefinite loops (like repeating until the user enters an even number). As a result, C provides both to programmers.