c++ 教程:执行分支控制
大约 6 分钟
分支结构(Conditional Branching)
if 语句块
if (condition1) { // do this if condition1 is true } else if (condition2) { // else this if condition2 is true } else { // otherwise do this }
if (true) { cout << "yes\n"; } // yes if (false) { cout << "yes\n"; } // – if (23) { cout << "yes\n"; } // yes (23 → true) if (0) { cout << "yes\n"; } // – (0 → false)
int i = 0; cin >> i; if (i < 0) { cout << "negative\n"; } if else (i == 0) { cout << "zero\n"; } else { cout << "positive\n"; }
三元条件操作符
Result = Condition ? If-Expression : Else-Expression 如果条件满足结果为 If-Expression 的值, 否则为 Else-Expression 的值
int i = 8; int j = i > 10 ? 1 : 2; j: 2
int k = 20; int l = (k > 10) ? 1 : 2; l: 1
int b = true; double d = b ? 2.0 : 0.5; d: 2.0 double e = !b ? 2.0 : 0.5; e: 0.5
switch 语句块
int i = 0; int m = i % 5; switch (m) { case 0: // do this if m is 0 break; case 1: // do this if m is 1 case 3: // do this (also) if m is 1 or 3 break; default: // do this if m is not 0, 1 or 3 }
循环结构(Loop)
for 循环
for (initialization; condition; step) { … }
// prints 0 1 2 3 4 for (int i = 0; i < 5; ++i) { std::cout << i << ' '; }
for Range
for (variable : range) { … } 遍历容器中的元素, e.g., std::vector
std::vector<int> v {1,2,3,4,5}; // print all elements of vector to console for (int x : v) { std::cout << x << ' '; }
while 循环
while (condition) { … } 条件满足才会执行首次循环
//prints 5 6 7 8 9 int j = 5; while (j < 10) { std::cout << j << ' '; ++j; }
do while 循环
do { … } while (condition); 至少执行一次循环,条件判断前就会执行一次循环
//prints 10 9 8 … 1 executed until j ≤ 0 int j = 10; do { std::cout << j << ' '; --j; } while (j > 0);