Conditionally executes a statement repeatedly (at least once).
|
attr (optional)do statementwhile ( expression); | | |
|
[edit]Explanation
When control reaches ado statement, itsstatement will be executed unconditionally.
Every timestatement finishes its execution,expression will be evaluated and contextually converted tobool. If the result istrue,statement will be executed again.
If the loop needs to be terminated withinstatement, abreak statement can be used as terminating statement.
If the current iteration needs to be terminated withinstatement, acontinue statement can be used as shortcut.
As part of the C++forward progress guarantee, the behavior isundefined if a loop that is not atrivial infinite loop(since C++26) withoutobservable behavior does not terminate. Compilers are permitted to remove such loops.
[edit]Keywords
do,while
[edit]Example
#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 usedstd::string s="aba";std::sort(s.begin(), s.end()); dostd::cout<< s<<'\n';// expression statement is the loop bodywhile(std::next_permutation(s.begin(), s.end()));}
Output:
[edit]See also