8-1 控制介绍
当程序运行时,CPU从main()函数的开头开始执行,依次执行若干条语句(默认按顺序执行),最终在main()函数结束时程序终止。CPU执行的具体语句序列称为程序的执行路径execution path(简称路径path)。
考虑以下程序:
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int x{};
std::cin >> x;
std::cout << "You entered " << x << '\n';
return 0;
}

该程序的执行路径依次包含第5、7、8、10和12行。这是直线程序的典型示例。直线程序straight-line program每次运行时都遵循相同路径(以相同顺序执行相同语句)。
然而这往往不符合我们的需求。例如当用户输入无效内容时,我们通常希望引导其重新选择。直线程序无法实现此功能——用户可能反复输入错误内容,因此需要引导重新选择的次数在运行前无法确定。
所幸C++提供了多种控制流语句control flow statements(亦称流程控制语句flow control statements),这类语句允许程序员改变程序的常规执行路径。你已在第4.10节——if语句介绍中接触过典型示例——if语句仅在条件表达式为真时执行特定语句。
当控制流语句使执行点跳转至非顺序语句时,这种行为称为分支branching。
流控制语句的分类
| Category | Meaning | Implemented in C++ by |
|---|---|---|
| Conditional statements | Causes a sequence of code to execute only if some condition is met. | if, else, switch |
| Jumps | Tells the CPU to start executing the statements at some other location. | goto, break, continue |
| Function calls | Jump to some other location and back. | function calls, return |
| Loops | Repeatedly execute some sequence of code zero or more times, until some condition is met. | while, do-while, for, ranged-for |
| Halts | Terminate the program. | std::exit(), std::abort() |
| Exceptions | A special kind of flow control structure designed for error handling. | try, throw, catch |
在本章中,我们将详细探讨所有这些类别,但异常处理除外(哈哈),我们将在未来的章节(第27章)专门讨论它。
在本章之前,程序能实现的功能相当有限。掌握程序流程控制(尤其是循环结构)后,各种精彩应用便触手可及!你将不再局限于玩具程序——真正有实用价值的程序即将诞生。
真正的乐趣此刻开启。让我们开始吧!

浙公网安备 33010602011771号