From cppreference.com
Conditionally executes a statement repeatedly (at least once).
Syntax
attr(optional)dostatementwhile (expression);Explanation
When control reaches a do statement, its statement will be executed unconditionally.
Every time statement finishes its execution, expression will be evaluated and contextually converted to bool. If the result is true, statement will be executed again.
If the loop needs to be terminated within statement, a
can be used as terminating statement.
If the current iteration needs to be terminated within statement, a
can be used as shortcut.
Notes
As part of the C++
, the behavior is
if a loop that is not a
(since C++26) without
does not terminate. Compilers are permitted to remove such loops.
Keywords
,
Example
Run this code
#include<algorithm>#include<iostream>#include<string>intmain(){intj=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::strings="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:
4 6 8 10 aab aba baa See also