It’s not necessary to use braces in the do
...while
statement if there’s only one statement in the body; however, most programmers include the braces to avoid confusion between the while
and do
...while
statements. For example,
while ( condition )
normally is regarded as the header of a while
statement. A do
...while
with no braces around the single statement body appears as
do
statement
while ( condition );
which can be confusing. You might misinterpret the last line—while(
condition );
—as a while
statement containing as its body an empty statement. Thus, the do
...while
with one statement often is written as follows to avoid confusion:
do
{
statement
} while ( condition );