将一段代码重复执行,就会用到循环语句,常用的循环语句有while 、for。先回顾一下while循环
while loop
// Syntax :while( expression ){//...}
while关键词后面跟表达式,表达式就是一个条件,如果条件成立,就会执行花括号内部的程序。
If the condition is true, the statement (loop body) will be executed.
跟if不同的是,花括号内部程序执行结束,会继续判断条件是否成立,如果还是成立,还会继续执行代码,直到条件不成立。如果该条件一直为true,那么该循环就会陷入死循环中,要极力避免此种情况。
#include <iostream>using namespace std;int main(){int num = 10;while (num > 0){cout << "num = " << num << endl;num--;}return 0;}
do-while loop
The test takes place after each iteration in a do-while loop.
The test takes place before each iteration in a while loop.
int num = 10;do{cout << "num = " << num << endl;num--;}while (num > 0);
do-while语法中,花括号内部的程序会先执行,然后判断条件是否成立。无论条件是否成立,都会先执行括号内的程序。
break and continue
如果我们想停止循环,可以用break语句
int num = 10;while (num > 0){if (num == 5)break;cout << "num = " << num << endl;num--;}
Skip the remaining part of the loop body and continue the next iteration.
int num = 10;while (num > 0){if (num == 5)continue;cout << "num = " << num << endl;num--;}
continue之后,当前循环停止,继续下次循环,上面代码中num=5 不会打印,会陷入死循环。
So,The Condition, Be Careful!
Can you find any problem from the down code?
size_t num = 10;while(num >= 0){cout << "num = " << num << endl;num--;}
size_t是无符号整数,当num自减到0时,在—的话,理论上是负数,但是其是无符号整数,—的话真实值是能表示的最大的整数。
bool flag = true;int count = 0;while(flag = true){cout << "count = " << count++ << endl;// and do sthif (count == 10) //meet a conditionflag = false; //set flag to false to break the loop}
flag=true 是赋值操作,而不是判断条件;
这是不会发生编译错误的
- Expression 3+4 has a value;
- Expression a+b has a value;
- Expression (a==b) has value (true or false);
- a=b is an assignment赋值操作, also an expression and has a value
b
The follow code can be compiled successfully!
int b = 0;int m = (b = 8);cout << "m="<< m << endl;
