Namespaces
Variants

do - while loop

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
while
do-while
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

Führt eine Anweisung bedingt wiederholt aus (mindestens einmal).

Inhaltsverzeichnis

Syntax

attr  (optional) do statement while ( expression );
attr - (since C++11) beliebig viele Attribute
expression - ein Ausdruck
statement - eine Anweisung (typischerweise eine zusammengesetzte Anweisung)

Erklärung

Wenn die Steuerung eine do -Anweisung erreicht, wird ihr statement bedingungslos ausgeführt.

Jedes Mal, wenn statement seine Ausführung beendet, wird expression ausgewertet und kontextuell zu bool konvertiert. Wenn das Ergebnis true ist, wird statement erneut ausgeführt.

Wenn die Schleife innerhalb der Anweisung beendet werden muss, kann eine break Anweisung als abschließende Anweisung verwendet werden.

Wenn die aktuelle Iteration innerhalb einer statement beendet werden muss, kann eine continue statement als Abkürzung verwendet werden.

Hinweise

Im Rahmen der C++ Fortschrittsgarantie ist das Verhalten undefiniert , wenn eine Schleife , die keine triviale Endlosschleife ist (seit C++26) ohne beobachtbares Verhalten nicht terminiert. Compilern ist es erlaubt, solche Schleifen zu entfernen.

Schlüsselwörter

do , while

Beispiel

#include <algorithm>
#include <iostream>
#include <string>
int main()
{
    int j = 2;
    do // compound statement is the loop body
    {
        j += 2;
        std::cout << j << ' ';
    }
    while (j < 9);
    std::cout << '\n';
    // common situation where do-while loop is used
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do std::cout << s << '\n'; // expression statement is the loop body
    while (std::next_permutation(s.begin(), s.end()));
}

Ausgabe:

4 6 8 10
aab
aba
baa

Siehe auch

C-Dokumentation für do-while