在没有 {} 的情况下做 while 循环

do while loop without {}

下面编写 do while 循环的语法是否包含单个语句而不像其他循环那样使用大括号 while, for, etc. 正确?我得到了所需的输出,但我想知道这是否有任何未定义的行为。

int32_t i = 1;
do 
    std::cout << i << std::endl;
while(++i <= 10);

cppreference表示与do while相同,与whileif等相同。

相关语法:

attr (optional) do statement while ( expression ) ;

  • attr(C++11) - any number of attributes
  • expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
  • statement - any statement, typically a compound statement, which is the body of the loop

这里的关键是语句通常是用花括号括起来的复合语句,但不一定如此。

与那些结构一样,即使只有一行,我也更喜欢大括号,但很高兴知道它有效。

不,完全没问题! C++ 中任何需要大括号但找不到大括号的循环都会考虑第一行并继续。

do-while 构造的主体必须是 statement

attr(optional) do statement while ( expression ) ;

attr(C++11) - any number of attributes

expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.

statement - any statement, typically a compound statement, which is the body of the loop

cppreference 注意这个语句通常是一个复合语句,它是一个用花括号括起来的块。

Compound statements or blocks are brace-enclosed sequences of statements.

但是,该语句也可以只是一个以分号结尾的表达式,您的示例就是这种情况。

如果 do-whileiffor 中只有一个语句,则不需要大括号

do
  statement;   
while (cond)

相同
do   
{
  statement;   
}
while (cond)

另一方面

同样

if(cond)
     statement;

一样

if(cond)
{
     statement;
}

如果你写

if(cond)
     statement1;
     statement2;

那么这将被视为

if(cond)
{
     statement1;
}
statement2;

给出了 do-while 循环的语法 here:

do statement while ( expression ) ;

statement allows for a expression-statement的语法:

statement:

attribute-specifier-seq opt expression-statement

表达式语句:

expression opt ;

所以 do-while 的主体不需要在内部 {},并且您的代码是有效的。

回答这个问题的原始资源应该是 C++ 标准:http://www.open-std.org/jtc1/sc22/wg21/docs/standards。 在 C++17 中,9.5 迭代语句 [stmt.iter] 表示 do 接受语句:

do statement while ( expression ) ;

所以这绝对没问题。

9.3 复合语句或块 [stmt.block] says

So that several statements can be used where one is expected, the compound statement (also, and equivalently, called “block”) is provided.

所以人们 tend/like 将 { ... } 用于 do 语句。