Namespaces
Variants
Views
Actions

while loop

From cppreference.com
< cpp‎ | language
Revision as of 13:58, 1 May 2013 by Cubbi (Talk | contribs)

Executes a Template:sparam repeatedly, until the value of Template:sparam becomes false. The test takes place before each iteration.

Contents

Syntax

Template:sparam(optional) while ( Template:sparam ) Template:sparam
Template:sparam(C++11) - any number of attributes
Template:sparam - 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.
Template:sparam - any statement, typically a compound statement, which is the body of the loop

Notes

If Template:sparam is a single statement (not a compound statement), the scope of variables declared in it is limited to the while loop as if it was a compound statement, in other words,

while(--x >= 0)
    int i;
// i goes out of scope

is the same as

while(--x >= 0) {
    int i;
} // i goes out of scope

If Template:sparam is a declaration such as T t = x, the declared variable is only in scope in the body of the loop, and is destroyed and recreated on every iteration, in other words, such while loop is equivalent to

label:
{ // start of condition scope
    T t = x;
    if (t) {
        statement
        goto label; // calls the destructor of t
    }
}

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.

Keywords

while

Example

#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';
}

Output:

10
2 4 6 8 
Hello