A do while loop in C++ is an exit-controlled loop that runs its body first and checks the condition afterward. Because the check sits at the end, the body always executes at least once, even when the condition is false from the start. The loop repeats while the condition stays true and stops the moment it becomes false. Use it for menus, input validation, and retry logic where the first pass is mandatory.Every program eventually repeats something. A sensor has to be read again, a menu has to be shown again, a bus transaction has to be retried. The do while loop in C++ is built for one specific situation: the work must happen at least once, and only then do you decide whether to repeat it.
In this guide you will learn what a do while loop in C++ is, how its syntax and execution flow work, where it fits in real embedded firmware, and which mistakes cost beginners hours of debugging. Every example is complete, so you can compile it on your PC and later adapt the pattern for a microcontroller project.
do { ... } while (0) inside macros, so you will meet this construct even if you rarely write it yourself.Engineering insight: In code reviews, the useful question is not which loop looks nicer. It is: what should happen when there is zero work to do? If the honest answer is ‘still run once’, use a do while loop. If the answer is ‘do nothing’, use while or for.
do {
// statement(s) to repeat
} while (condition);
bool works: a comparison, a logical combination, a function call, or an integer (0 is false, anything else is true).Fact: The semicolon is part of the C++ grammar for this statement, so omitting it is a compile error.
Recommendation: Always use braces, even for a single statement. It prevents a classic bug when a second line is added later.
The execution flow has four steps:
+-------------------+
| Enter the loop |
+---------+---------+
|
v
+-------------------+
| Execute body |<--------+
+---------+---------+ |
| |
v |
+-------------------+ true |
| Evaluate condition|---------+
+---------+---------+
| false
v
+-------------------+
| Exit the loop |
+-------------------+
The compiler emits the body followed by one conditional branch back to the top. Optimizers often apply loop inversion, which rewrites a while loop as an if check plus a do while form, because that needs only one branch per iteration. So pick the loop for its meaning, not for speed. At -O2, equivalent loops frequently compile to the same machine code.
break, continue, and returnboolC++ has one do while syntax, but you will use it in a few common forms:
bool such as isValid or done changes.do { ... } while (true); exits only through break or return. In firmware, the main super loop is more commonly written as while (true) or for (;;).while.continue jumps to the condition, which can create infinite loops.Recommendation: Use do while only when the first pass is truly mandatory. Otherwise while or for is easier to read.
The do while loop in C++ shows up wherever an action must happen before its result can be judged:
The pattern is identical in each case: act, check, then decide whether to act again.
#include
int main() {
int count = 1;
do {
std::cout << "Count = " << count << std::endl;
++count; // update the variable that controls the condition
} while (count <= 5); // semicolon is mandatory
return 0;
}
Output: Count = 1 through Count = 5, one per line.
Explanation:
count is incremented.count <= 5 is checked after each pass.count becomes 6, the condition is false and the loop ends.#include
int main() {
int i = 10;
do {
std::cout << "Body ran with i = " << i << std::endl;
++i;
} while (i < 5); // false from the very beginning
return 0;
}
Output: Body ran with i = 10 (printed exactly once).
Explanation: This is the defining behavior of the do while loop in C++. A while (i < 5) loop would print nothing.
#include
#include
int main() {
int value = 0;
bool valid = false;
do {
std::cout << "Enter a value between 1 and 10: "; if (std::cin >> value && value >= 1 && value <= 10) {
valid = true;
} else {
if (std::cin.eof()) {
return 1; // input closed, avoid an endless loop
}
std::cin.clear(); // reset the error state
std::cin.ignore(std::numeric_limits::max(), '\n');
std::cout << "Invalid input. Try again." << std::endl;
}
} while (!valid);
std::cout << "You entered: " << value << std::endl;
return 0;
}
Explanation:
valid is a flag-controlled exit condition with a readable name.clear() and ignore() remove bad input from the stream. Without them, a letter typed by mistake causes an endless loop.eof() check protects against closed input, such as a piped file that ends early.#include
#include
// Simulated peripheral: the first two reads fail, the third succeeds.
static bool sensor_read(std::uint16_t &out) {
static int calls = 0;
++calls;
if (calls < 3) {
return false; // pretend the bus was busy
}
out = 512; // pretend ADC value
return true;
}
int main() {
constexpr int kMaxRetries = 5;
int attempt = 0;
bool ok = false;
std::uint16_t reading = 0;
do {
ok = sensor_read(reading); // always try at least once
++attempt;
} while (!ok && attempt < kMaxRetries);
if (ok) {
std::cout << "Reading = " << reading << " after " << attempt << " attempt(s)" << std::endl;
} else {
std::cout << "Sensor not responding after " << attempt << " attempts" << std::endl;
}
return 0;
}
Output: Reading = 512 after 3 attempt(s)
Explanation:
attempt < kMaxRetries caps the retries so a dead sensor cannot hang the firmware.std::uint16_t makes the data width explicit, which matters on 8-bit and 32-bit targets alike.#include
#include
// On real hardware this is a memory-mapped status register.
// volatile stops the compiler from caching the value in a CPU register.
volatile std::uint32_t UART_STATUS = 0;
constexpr std::uint32_t TX_READY = (1u << 7);
bool wait_for_tx_ready(std::uint32_t max_polls) {
std::uint32_t polls = 0;
do {
if ((UART_STATUS & TX_READY) != 0u) {
return true; // flag is set, stop waiting
}
++polls;
} while (polls < max_polls);
return false; // timed out
}
int main() {
std::cout << "Flag clear: " << wait_for_tx_ready(1000) << std::endl; // prints 0
UART_STATUS = TX_READY; // simulate hardware
std::cout << "Flag set: " << wait_for_tx_ready(1000) << std::endl; // prints 1
return 0;
}
Explanation:
max_polls is 0. A while version would skip the check entirely.volatile tells the compiler the value can change outside the program flow, so every poll really reads the register.#define LED_PULSE(pin) \
do { \
led_on(pin); \
delay_ms(100); \
led_off(pin); \
} while (0)
Explanation: The wrapper makes a multi-statement macro behave like one statement. if (error) LED_PULSE(2); else idle(); compiles correctly, whereas a macro written as a bare { ... } block would break the else. You will see this pattern in the Linux kernel and in vendor HAL headers such as STM32 HAL. In new C++ code, prefer an inline function.
| Feature | while | do while | for |
|---|---|---|---|
| Loop type | Entry-controlled | Exit-controlled | Entry-controlled |
| Condition checked | Before the body | After the body | Before the body |
| Minimum executions | 0 | 1 | 0 |
| Semicolon after condition | No | Yes | No |
| Variable in condition | Allowed, for example while (int x = f()) | Not allowed | Allowed in the init-statement |
| Best suited for | Unknown count, may not run at all | Mandatory first pass, retries, menus | Known iteration count |
| Typical embedded use | Wait for an event, drain a buffer | Retry a transfer, poll a flag once | Iterate over arrays and registers |
while or for.done or isValid, so the condition at the bottom reads like a sentence.if or a while before touching buffers, arrays, or containers.volatile, and only those, since extra volatile blocks optimization.while (i++ < 10) style tricks stay out of production code.std::uint8_t and std::uint32_t for counters and flags in firmware.-Wall -Wextra and follow your team’s standard, for example MISRA C++ or the C++ Core Guidelines.| Mistake | Why it happens | Impact | How professionals avoid it |
|---|---|---|---|
Missing semicolon after while (condition) | Habit from while and for, which take none | Compile error | Compile often and use clang-format so the error surfaces immediately |
| Using a body variable in the condition | Assuming the body’s scope extends to the condition | Compile error: variable not declared | Declare the variable before do |
continue before updating the loop variable | continue jumps to the condition, not the top | Infinite loop, board looks frozen | Update the variable first, or restructure the logic |
| Using do while on possibly empty data | The body runs before any check | Out-of-bounds read or garbage value | Check the size with if, or use while |
| No timeout in hardware polling | Assuming the peripheral always responds | System hang until a watchdog reset | Add a poll counter or timer, and an error path |
Not clearing a failed cin state | Bad input stays in the stream | Endless prompt loop | Call clear() and ignore(), and check eof() |
int i = 0;
do {
if (i == 3) {
continue; // jumps to the condition check, ++i is skipped
}
std::cout << i << std::endl;
++i;
} while (i < 6); // i stays 3 forever
do {
int reading = read_sensor();
} while (reading > 100); // error: 'reading' was not declared in this scope
// Fix: declare it before the loop
int reading = 0;
do {
reading = read_sensor();
} while (reading > 100);
objdump -d or the debugger’s disassembly view) to confirm the branch back to the loop start.do { ... } while (--n); works when n is at least 1. On some architectures, including ARM, comparing against zero can save an instruction. Verify in the disassembly at your optimization level.std::cout and printf can add significant flash and RAM on a microcontroller and slow every iteration.The do while loop in C++ does one job better than any other loop: it guarantees a first pass before the condition decides what happens next. That single rule explains its syntax, its mandatory semicolon, and its best uses in menus, input validation, retry logic, and hardware polling.
Remember three habits. Update the variables that control the condition, never poll hardware without a timeout, and prefer while or for when the work may need to run zero times. Step through the examples above in a debugger, and you will handle the do while loop in C++ confidently in interviews and in production firmware.
A do while loop in C++ is an exit-controlled loop that executes its body first and then checks a condition. If the condition is true, the body runs again. If it is false, the loop ends. Because the test comes last, the body always runs at least once, which makes it ideal for menus, input validation, and retry logic.
A while loop tests its condition before running the body, so it can run zero times. A do while loop tests the condition after the body, so it always runs at least once. Choose while when the work may be unnecessary, and choose do while when the first execution is required regardless of the condition.
Yes. Control enters the body before the condition is ever evaluated, so the first pass is guaranteed even when the condition is false from the start. Only a break, a return, an exception, or program termination inside the body can stop that first pass from completing.
The do while construct is a single statement, and its grammar ends with a semicolon after the condition. Leaving it out causes a compile error. The opposite mistake is also common: adding an extra semicolon after a normal while condition silently creates an empty loop body, which is a frequent source of bugs.
Yes. Embedded code uses it to retry bus transactions, to poll a peripheral status flag at least once, and to wrap multi-statement macros as do { } while (0). When you poll hardware, always add a timeout or poll counter so a missing response cannot freeze the firmware.
Indian Institute of Embedded Systems – IIES