# 条件语句（计算机编程）

在计算机编程中，条件语句是一种构造，它根据布尔条件是否为真来执行若干语句之一，或对若干表达式之一求值。最常见的形式是 if 语句，在许多语言中写作 `if` *条件* `then` *语句* `else` *语句*；条件语句也以返回值的表达式形式出现，以多路 case 或 switch 构造的形式出现，以及以在程序运行前丢弃代码的编译期变体形式出现。

| 关键事实 | 详情 |
|---|---|
| 核心语义 | 对条件求值；若为真则执行 then 分支，若为假则执行 else 分支（若存在），否则越过该语句继续执行<sup>[1](https://learn.microsoft.com/en-us/cpp/c-language/if-statement-c?view=msvc-170)</sup> |
| 结构化起源 | ALGOL 60（1960）使 `if`-`then`-`else` 成为可组合、可嵌套的语句，其主体可以是整个块，与 `begin`-`end` 块及 `for` 语句并列<sup>[2](https://codearchaeology.dev/languages/algol-60/04-control-flow/)</sup> |
| 条件表达式 | 约翰·麦卡锡（John McCarthy）的记法 \( (p_1 \to e_1,\ p_2 \to e_2,\ \ldots,\ p_n \to e_n) \) 取第一个谓词 \( p_i \) 为真的 \( e_i \) 的值，对应于 ALGOL 60 的链式写法 `if p1 then e1 else if p2 then e2 ...`<sup>[3](https://doi.org/10.1016/s0049-237x(09)70099-0)</sup> |
| 现代语言中的表达式形式 | Python 的 `x if C else y` 先对 `C` 求值；Rust 将 `if` 视为表达式，其各分支必须具有相同类型<sup>[4](https://docs.python.org/3/reference/expressions.html?highlight=number+conversion)</sup><sup> • </sup><sup>[5](https://doc.rust-lang.org/nightly/reference/expressions/if-expr.html)</sup> |
| 短路条件 | 在短路求值中，仅当第一个操作数不足以确定表达式的值时，才对 `&&` 或 `||` 的第二个操作数求值<sup>[6](https://arxiv.org/abs/1010.3674)</sup> |
| 编译期选择 | C++ 在 C++17 中加入 `if constexpr`，在 C++23 中加入 `if consteval`，在特定条件下于编译期丢弃未选取的分支<sup>[7](https://en.cppreference.com/cpp/language/if)</sup> |

## 条件语句如何执行

在 C 族语言中，`if` 语句控制条件分支：对控制表达式求值（包括其全部副作用），若其值非零则执行主体，若有 `else` 子句则在其值为零时执行第二条语句。随后控制权交给下一条语句，除非遇到 `break`、`continue` 或 `goto` 介入<sup>[1](https://learn.microsoft.com/en-us/cpp/c-language/if-statement-c?view=msvc-170)</sup>。条件本身也可以是一个声明，如 C++17 的 `if (auto it = m.find(10); it != m.end())`，它将所声明的变量作用域限定在该语句内<sup>[7](https://en.cppreference.com/cpp/language/if)</sup>。

条件不必严格为布尔值。C 接受任何标量表达式并将其与零比较；Rust 要求每个条件操作数都是布尔表达式或 `let` 模式匹配，并允许用 `&&` 连接多个操作数<sup>[1](https://learn.microsoft.com/en-us/cpp/c-language/if-statement-c?view=msvc-170)</sup><sup> • </sup><sup>[5](https://doc.rust-lang.org/nightly/reference/expressions/if-expr.html)</sup>。

## 语句与表达式

**语句选择动作。** 在 [ALGOL 60](https://www.edgepedia.org/zh/algol-60) 中，条件语句 `if B then S1 else S2` 在语句之间做选择，而由于任何语句都可以是 `begin`-`end` 块，一个分支可以包含一整串声明和语句<sup>[2](https://codearchaeology.dev/languages/algol-60/04-control-flow/)</sup><sup> • </sup><sup>[8](https://www.algol60.org/reports/algol60_rr.pdf)</sup>。这种可组合性正是其新颖之处：语句是递归的，可以嵌套到任意深度，而 Algol 是第一个用巴科斯-瑙尔范式（Backus-Naur form）形式文法定义的语言<sup>[9](https://xavierleroy.org/control-structures/book/main004.html)</sup>。

**表达式选择值。** ALGOL 也有条件表达式：在 `IF BOOL THEN 47 ELSE 95` 中，条件为真时选取 THEN 之后的表达式，为假时选取 ELSE 之后的表达式，若某分支本身又是条件式则重复该过程<sup>[10](https://www.support.unisys.com/aseries/docs/ClearPath-MCP-21.0/86000098-519/section-000026234.html)</sup>。领导 [Lisp](https://www.edgepedia.org/zh/lisp-programming-language) 设计的斯坦福计算机科学家约翰·麦卡锡将这一形式置于其 1960 年代关于计算的数学理论的中心，用条件表达式定义阶乘等递归函数，并指出当谓词为真时，所选取的值是“甚至不看”另一分支而取得的<sup>[11](https://www-formal.stanford.edu/jmc/towards/node7.html)</sup>。

现代语言在提供何种形式上各有不同。Python 保留了语句形式（`if`/`elif`/`else` 加缩进的语句组），并增加了条件表达式，有时称为三元运算符，写作 `x if C else y`<sup>[4](https://docs.python.org/3/reference/expressions.html?highlight=number+conversion)</sup><sup> • </sup><sup>[12](https://docs.python.org/3.14/reference/compound_stmts.html)</sup>。C 用运算符形式 `e1 ? e2 : e3` 表示表达式，用 `if` 表示语句。Rust 只有表达式形式：`if` 求值为所执行块的值，若无块执行则为 `()`，且各分支必须类型一致，这使得 `let greeting = if rude { "sup nerd." } else { "hello, friend!" };` 可以成立<sup>[5](https://doc.rust-lang.org/nightly/reference/expressions/if-expr.html)</sup><sup> • </sup><sup>[13](https://doc.rust-lang.org/std/keyword.if.html)</sup>。

## 历史

第一个使用类似现代 `if` 构造的语言很可能是 Fortran I，其 IF 充当三路 goto 而非结构化分支<sup>[14](https://craftofcoding.wordpress.com/2017/04/29/the-evolution-of-if-i-from-fortran-i-to-algol-60/)</sup>。设计 ALGOL 60 时，结构化编程尚未成为既定理念，大多数同期语言依赖标号和 `goto`；ALGOL 60 则反其道而行，给程序员提供了一套小巧的可组合工具：`if`-`then`-`else`、`for` 语句和块<sup>[2](https://codearchaeology.dev/languages/algol-60/04-control-flow/)</sup>。

两个人塑造了这一构造的形式。麦卡锡向 CACM 论坛寄去一份关于条件表达式的提案，讨论 Algol 60 应包含哪些内容，而 Algol 60 所采纳的 `if ... then ... else` 是由[约翰·巴科斯](https://www.edgepedia.org/zh/john-backus)（John Backus）建议的<sup>[15](https://cs.clarku.edu/~fgreen/courses/cs170/mccarthy.pdf)</sup>。麦卡锡的多路记法 \( (p_1 \to e_1, \ldots, p_n \to e_n) \) 返回第一个为真的谓词所对应的 \( e \) 的值，例如 \( (4 < 3 \to 7,\ 2 > 3 \to 8,\ 2 < 3 \to 9,\ 4 < 5 \to 7) = 9 \)<sup>[3](https://doi.org/10.1016/s0049-237x(09)70099-0)</sup>。结构化条件语句与 Algol 风格 `goto` 的结合随后成为发表算法的首选方式；早在 1960 年，《ACM 通讯》（Communications of the ACM）就规定为此目的使用 Algol 而非流程图<sup>[9](https://xavierleroy.org/control-structures/book/main004.html)</sup>。

## 嵌套与悬空 else

当 `if` 语句嵌套时，每个 `else` 都必须与正确的 `then` 配对。优利系统的 ALGOL 手册明确要求这种对应关系：若程序希望某个 `else` 与外层 `then` 配对，则内层 `if` 必须用 `begin` 和 `end` 包裹<sup>[16](https://www.support.unisys.com/aseries/docs/ClearPath-MCP-21.0/86000098-519/section-000026430.html)</sup>。各语言以不同方式解决这一歧义。Python 要求嵌套的 `if` 语句缩进，因此续接子句总是以不能开始语句的关键字开头，不会产生歧义<sup>[12](https://docs.python.org/3.14/reference/compound_stmts.html)</sup>。C 族语言的文法将裸 `else` 绑定到最近的未匹配 `if`。

深层嵌套对读者的影响尚有争议。1986 年的一项实验将 148 名计算机科学学生分成两组，一组使用大量深层嵌套 IF-THEN-ELSE 结构的程序，另一组使用功能等价但没有这些结构的程序，结果发现两组在理解题上的平均表现没有显著差异<sup>[17](https://www.sciencedirect.com/science/article/pii/0164121286900038)</sup>。缩进是另一个因素：一项随机试验测量了受试者阅读 Java 中生成的七层嵌套 if 语句的时间，发现缩进有益的经验基础一直薄弱，并构建了一个可读性模型，其中未缩进的代码迫使读者扫描 then 和 else 分支，而缩进的代码则让读者可以跳过它们<sup>[18](https://link.springer.com/article/10.1007/s10664-024-10531-y)</sup>。

## 条件求值与短路

由 `&&` 和 `||` 构成的条件通常惰性求值。[短路求值](https://www.edgepedia.org/zh/short-circuit-evaluation)是这样一种语义：仅当第一个参数不足以确定表达式的值时，才对第二个参数求值；在编程中它被广泛使用，以顺序合取和析取作为原始联结词<sup>[6](https://arxiv.org/abs/1010.3674)</sup>。这种做法以约翰·麦卡锡命名为麦卡锡求值。C# 通过将 `&&` 和 `||` 作为 `&` 和 `|` 处理，再应用条件短路规则来实现它们，而用户定义类型可能达到两个运算符都不短路的状态<sup>[19](https://www.ecma-international.org/wp-content/uploads/ECMA-334_6th_edition_june_2022.pdf)</sup>。

求值顺序与异常控制流相互作用。在用于网络数据平面编程的 P4 语言中，若 `table.apply()` 作为 `if` 语句的表达式时导致退出，则 then 和 else 分支都不执行；在条件表达式 `e1 ? e2 : e3` 中，`e2` 和 `e3` 都不求值<sup>[20](https://p4lang.github.io/p4-spec/docs/P4-16-working-spec.html)</sup>。

## 实践中的条件语句

条件语句是软件开发中最常被修改的代码之一。一项关于 Qt 和 [OpenStack](https://www.edgepedia.org/zh/openstack) 项目代码评审的实证研究分析了 if 语句的修改，发现最常被修改的符号是圆括号 `( )`、点号 `.` 和取反 `!`，并存在项目特定的修复模式，例如用函数调用替换 `!`<sup>[21](https://www.jstage.jst.go.jp/article/transinf/E101.D/11/E101.D_2018EDP7004/_article)</sup>。

新手代码表现出反复出现的结构性缺陷。一项研究使用 qChecker 工具分析了 398 名一年级学生的 41,032 份 Python 提交，识别出 15 种条件反模式；最常见的是“if/else 返回布尔值”，即两个分支都返回本可直接返回的布尔值，以及“令人困惑的 else”，即嵌套 if-else 可以展平，因为外层 else 不含其他内容，这两者合计占所检测到的 7,491 个反模式的 57.1%<sup>[22](https://arxiv.org/abs/2410.18989)</sup>。

## 编译期条件语句

C++ 将运行时条件语句扩展到编译期。`constexpr if` 语句（C++17）要求其条件为常量表达式；若结果为真则丢弃假分支，而在模板实体中，不依赖于值的被丢弃语句根本不会被实例化，这允许诸如 `if constexpr (sizeof...(rs) > 0) g(rs...)` 的代码，否则对空参数包而言将是非良构的<sup>[7](https://en.cppreference.com/cpp/language/if)</sup>。C++23 增加了 `if consteval`，它根据语句是否在明显常量求值上下文中求值来选择分支<sup>[7](https://en.cppreference.com/cpp/language/if)</sup>。这些与预处理器的 `#if` 指令不同，后者在编译前选择文本，而 `if constexpr` 明确不是它们的替代品：模板之外的被丢弃语句仍会被完整检查<sup>[7](https://en.cppreference.com/cpp/language/if)</sup>。

## References

1. [if Statement (C), Microsoft Learn](https://learn.microsoft.com/en-us/cpp/c-language/if-statement-c?view=msvc-170)
2. [Control Flow in ALGOL 60, CodeArchaeology](https://codearchaeology.dev/languages/algol-60/04-control-flow/)
3. [A Basis for a Mathematical Theory of Computation (1962), John McCarthy](https://doi.org/10.1016/s0049-237x(09)70099-0)
4. [6. Expressions, Python 3 documentation](https://docs.python.org/3/reference/expressions.html?highlight=number+conversion)
5. [If expressions, The Rust Reference](https://doc.rust-lang.org/nightly/reference/expressions/if-expr.html)
6. [Short-circuit logic, arXiv:1010.3674](https://arxiv.org/abs/1010.3674)
7. [if statement, cppreference.com](https://en.cppreference.com/cpp/language/if)
8. [Revised report on the algorithmic language ALGOL 60](https://www.algol60.org/reports/algol60_rr.pdf)
9. [Chapter 1: Early programming languages, Xavier Leroy](https://xavierleroy.org/control-structures/book/main004.html)
10. [Conditional Expressions, ALGOL Programming Reference Manual, Unisys](https://www.support.unisys.com/aseries/docs/ClearPath-MCP-21.0/86000098-519/section-000026234.html)
11. [Using Conditional Expressions to Define Functions Recursively, John McCarthy](https://www-formal.stanford.edu/jmc/towards/node7.html)
12. [8. Compound statements, Python 3 documentation](https://docs.python.org/3.14/reference/compound_stmts.html)
13. [Keyword if, Rust standard library documentation](https://doc.rust-lang.org/std/keyword.if.html)
14. [The evolution of if (i): pre-Fortran to Algol 60, The Craft of Coding](https://craftofcoding.wordpress.com/2017/04/29/the-evolution-of-if-i-from-fortran-i-to-algol-60/)
15. [McCarthy, Recursive Functions (course PDF, Clark University)](https://cs.clarku.edu/~fgreen/courses/cs170/mccarthy.pdf)
16. [Forms of the IF Statement, ALGOL Programming Reference Manual, Unisys](https://www.support.unisys.com/aseries/docs/ClearPath-MCP-21.0/86000098-519/section-000026430.html)
17. [Are deeply nested conditionals less readable? Journal of Systems and Software, 1986](https://www.sciencedirect.com/science/article/pii/0164121286900038)
18. [Indentation and reading time: a randomized control trial, Empirical Software Engineering](https://link.springer.com/article/10.1007/s10664-024-10531-y)
19. [ECMA-334, 6th edition, June 2022 (C# standard)](https://www.ecma-international.org/wp-content/uploads/ECMA-334_6th_edition_june_2022.pdf)
20. [P4-16 Language Specification, P4 Language Consortium](https://p4lang.github.io/p4-spec/docs/P4-16-working-spec.html)
21. [How are IF-Conditional Statements Fixed Through Peer Code Review? IEICE Transactions](https://www.jstage.jst.go.jp/article/transinf/E101.D/11/E101.D_2018EDP7004/_article)
22. [Anti-patterns in Students' Conditional Statements, arXiv:2410.18989](https://arxiv.org/abs/2410.18989)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/conditional-computer-programming

English original: https://www.edgepedia.org/conditional-computer-programming
