将一段代码重复执行,就会用到循环语句,常用的循环语句有whilefor。先回顾一下while循环

while loop

  1. // Syntax :
  2. while( expression )
  3. {
  4. //...
  5. }

while关键词后面跟表达式,表达式就是一个条件,如果条件成立,就会执行花括号内部的程序。

If the condition is true, the statement (loop body) will be executed.
跟if不同的是,花括号内部程序执行结束,会继续判断条件是否成立,如果还是成立,还会继续执行代码,直到条件不成立。如果该条件一直为true,那么该循环就会陷入死循环中,要极力避免此种情况。

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int num = 10;
  6. while (num > 0)
  7. {
  8. cout << "num = " << num << endl;
  9. num--;
  10. }
  11. return 0;
  12. }

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.

  1. int num = 10;
  2. do
  3. {
  4. cout << "num = " << num << endl;
  5. num--;
  6. }while (num > 0);

do-while语法中,花括号内部的程序会先执行,然后判断条件是否成立。无论条件是否成立,都会先执行括号内的程序。

break and continue

如果我们想停止循环,可以用break语句

  1. int num = 10;
  2. while (num > 0)
  3. {
  4. if (num == 5)
  5. break;
  6. cout << "num = " << num << endl;
  7. num--;
  8. }

Skip the remaining part of the loop body and continue the next iteration.

  1. int num = 10;
  2. while (num > 0)
  3. {
  4. if (num == 5)
  5. continue;
  6. cout << "num = " << num << endl;
  7. num--;
  8. }

continue之后,当前循环停止,继续下次循环,上面代码中num=5 不会打印,会陷入死循环。
So,The Condition, Be Careful!

Can you find any problem from the down code?

  1. size_t num = 10;
  2. while(num >= 0)
  3. {
  4. cout << "num = " << num << endl;
  5. num--;
  6. }

size_t是无符号整数,当num自减到0时,在—的话,理论上是负数,但是其是无符号整数,—的话真实值是能表示的最大的整数。

  1. bool flag = true;
  2. int count = 0;
  3. while(flag = true)
  4. {
  5. cout << "count = " << count++ << endl;
  6. // and do sth
  7. if (count == 10) //meet a condition
  8. flag = false; //set flag to false to break the loop
  9. }

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!

  1. int b = 0;
  2. int m = (b = 8);
  3. cout << "m="<< m << endl;