do-while loop
suggest changeA do-while loop is very similar to a while loop, except that the condition is checked at the end of each cycle, not at the start. The loop is therefore guaranteed to execute at least once.
The following code will print 0
, as the condition will evaluate to false
at the end of the first iteration:
#include <iostream>
using namespace std;
auto main() -> int
{
int i =0;
do
{
std::cout << i;
++i;
} while (i < 0);
std::cout << std::endl;
}
0
Note: Do not forget the semicolon at the end of while(condition);
, which is needed in the do-while construct.
In contrast to the do-while loop, the following will not print anything, because the condition evaluates to false
at the beginning of the first iteration:
int i = 0;
while (i < 0)
{
std::cout << i;
++i;
}
std::cout << std::endl;
Note: A while loop can be exited without the condition becoming false by using a break
, goto
, or return
statement.
#include <iostream>
using namespace std;
auto main() -> int
{
int i = 0;
do
{
std::cout << i;
++i;
if (i > 5) {
break;
}
}
while (true);
std::cout << std::endl;
}
012345
A trivial do-while loop is also occasionally used to write macros that require their own scope (in which case the trailing semicolon is omitted from the macro definition and required to be provided by the user):
#define BAD_MACRO(x) f1(x); f2(x); f3(x);
// Only the call to f1 is protected by the condition here
if (cond) BAD_MACRO(var);
#define GOOD_MACRO(x) do { f1(x); f2(x); f3(x); } while(0)
// All calls are protected here
if (cond) GOOD_MACRO(var);