Namespaces
Variants
Views
Actions

while loop

From cppreference.com
< cpp‎ | language
Revision as of 21:02, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
while loop
do-while loop
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Executes a loop.

Used where code needs to be executed several times while some condition is present.

Contents

Syntax

while ( Template:sparam ) Template:sparam

Explanation

Template:sparam shall be an expression, whose result is convertible to bool. It is evaluated before each execution of Template:sparam, which is only executed if the Template:sparam evaluates to true.

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()
{
    int i = 0;
    while (i < 10) i++;
 
    std::cout << i << '\n';
 
    int j = 2;
    while (j < 9) {
        std::cout << j << " ";
        j += 2;
    }
}

Output:

10
2 4 6 8