Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      do-while loop

      From cppreference.com
      <cpp‎ |language
       
       
      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
       
       

      Conditionally executes a statement repeatedly (at least once).

      Contents

      [edit]Syntax

      attr (optional)dostatementwhile (expression);
      attr -(since C++11) any number ofattributes
      expression - anexpression
      statement - astatement (typically a compound statement)

      [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.

      [edit]Notes

      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

      Run this code
      #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:

      4 6 8 10aabababaa

      [edit]See also

      C documentation fordo-while
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/do&oldid=172484"

      [8]ページ先頭

      ©2009-2025 Movatter.jp