C++中提供了顺序、选择、循环3种常用的流程控制结构,此外还支持goto
语句用于任意位置的程序跳转,这篇笔记我们简单介绍一下。
if语句可以根据表达式的值为true
或false
执行符合条件的分支结构,下面例子中,a == 10
分支会被执行。
#include <iostream>
int main() {
int a = 10;
if (a < 10) {
std::cout << "a is less than 10" << std::endl;
} else if (a == 10) {
std::cout << "a is equal to 10" << std::endl;
} else if (a > 10) {
std::cout << "a is greater than 10" << std::endl;
}
return 0;
}
if语句的表达式结果不一定是布尔类型,只要它是非0
的,那么就会被认为是true
。
#include <iostream>
int main() {
int a = 1;
if (a) {
std::cout << "a is true" << std::endl;
}
return 0;
}
三目运算符上一章节中我们已经介绍过,它也是一种选择分支结构,三目运算符也可以嵌套使用。
#include <iostream>
int main() {
int a = 10;
a < 10
? std::cout << "a is less than 10" << std::endl
: a == 10
? std::cout << "a is equal to 10" << std::endl
: std::cout << "a is greater than 10" << std::endl;
return 0;
}
switch case语句也是一种分支结构,它适用于分支较多的情况,不过switch case语句的表达式值必须是整型或字符型,此外所有case条件的结尾必须添加break
,否则多个分支可能被执行,这通常不符合预期。
#include <iostream>
int main() {
int a = 10;
switch (a) {
case 9:
std::cout << "a is equal to 9" << std::endl;
break;
case 10:
std::cout << "a is equal to 10" << std::endl;
break;
default:
std::cout << "other conditions..." << std::endl;
break;
}
return 0;
}
while语句用于表达循环逻辑,循环直到循环条件为false
。
#include <iostream>
int main() {
int a = 0;
while (a < 10) {
std::cout << a++ << std::endl;
}
return 0;
}
break
语句可以退出循环。
#include <iostream>
int main() {
int a = 0;
while (true) {
if (a == 10) {
break;
}
std::cout << a++ << std::endl;
}
return 0;
}
continue
可以跳过本轮循环,但循环仍将继续。
#include <iostream>
int main() {
int a = 0;
while (a < 10) {
if (a++ == 2) {
continue;
}
std::cout << a << std::endl;
}
return 0;
}
do while语句和while语句类似,但会先执行循环体再判断循环条件。
#include <iostream>
int main() {
int a = 0;
do {
std::cout << a++ << std::endl;
} while (a < 10);
return 0;
}
for语句的格式为for(起始表达式; 表达式条件; 末尾循环体语句)
,下面是一个例子。
#include <iostream>
int main() {
for (int i = 1; i < 10; i++) {
std::cout << i << std::endl;
}
return 0;
}
C++11引入了范围for语句,它常用于遍历容器(例如std::vector
)和数组中的元素。
#include <iostream>
int main() {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i: arr) {
std::cout << i << std::endl;
}
return 0;
}
goto
语句可以让程序执行流程跳转到任意位置,这和汇编的JMP指令类似,下面是一个例子。
#include <iostream>
int main() {
int a = 0;
loop:
std::cout << a++ << std::endl;
if (a < 10) {
goto loop;
}
return 0;
}
大多数人都极力反对goto
语句的使用,因为它太过灵活,很容易让代码的执行流程出现意外情况,goto
语句在绝大多数程序中都是不应该出现的。