首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

while loop

重复执行语句,直到条件的值变为false测试在每次迭代之前进行。

句法

attr(optional) while ( condition ) statement

?

?

attr(C++11)

-

any number of attributes

condition

-

any expression which is contextually convertible to bool or a declaration of a single variable with a brace-or-equals initializer. This expression is evaluated before each iteration, and if it yields false, the loop is exited. If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

statement

-

any statement, typically a compound statement, which is the body of the loop

解释

如果语句是单个语句%28,而不是复合语句%29,则其中声明的变量范围仅限于while循环,就好像它是复合语句一样,

二次

代码语言:javascript
复制
while (--x >= 0)
    int i;
// i goes out of scope

二次

和。

二次

代码语言:javascript
复制
while (--x >= 0) {
    int i;
} // i goes out of scope

二次

如果条件是一个声明,如T t = x,声明的变量仅在循环主体中的作用域中,并且在每次迭代中被销毁和重新创建,换句话说,When循环相当于。

二次

代码语言:javascript
复制
label:
{ // start of condition scope
    T t = x;
    if (t) {
        statement
        goto label; // calls the destructor of t
    }
}

二次

如果需要在某个点终止循环的执行,断续语句可用作终止语句。

如果循环的执行需要在循环主体的末尾继续,继续语句可以用作快捷方式。

注记

作为C++的一部分前进保障,行为是未定如果循环没有可观察行为%28不调用I/O函数、访问易失性对象或执行原子或同步操作%29不终止。编译器可以删除这些循环。

关键词

while...

二次

代码语言:javascript
复制
#include <iostream>
 
int main() {
    // while loop with a single statement
    int i = 0;
    while (i < 10)
         i++;
    std::cout << i << '\n';
 
    // while loop with a compound statement
    int j = 2;
    while (j < 9) {
        std::cout << j << ' ';
        j += 2;
    }
    std::cout << '\n';
 
   // while loop with a declaration condition
   char cstr[] = "Hello";
   int k = 0;
   while (char c = cstr[k++])
       std::cout << c;
   std::cout << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
10
2 4 6 8 
Hello

二次

另见

c同时提供文件

*。

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com