为什么 for 语句中 init 语句末尾的分号是强制性的?

san*_*zio 1 c++ syntax

这是 C++17 标准定义 for 语句的方式:

for ( init-statement condition??? ; expression???  ) statement
Run Code Online (Sandbox Code Playgroud)

我还查看了https://en.cppreference.com/w/cpp/language/for

attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
Run Code Online (Sandbox Code Playgroud)

因此,我只能理解在使用 for 循环时 init-statement 不是可选的。换句话说,必须在标头内初始化一些变量才能使用这种控制机制流。好吧,情况似乎并非如此,因为当我键入诸如

for (; a != b; ++a)
Run Code Online (Sandbox Code Playgroud)

假设我已经定义了这些变量,它运行得很好。我不仅没有在头文件中声明变量,还引用了之前在循环外定义的其他变量。如果我要提供一个 init 语句,它的对象只能在 for 循环内使用,但似乎我可以使用在其他地方声明的变量就好了。

得出这个结论后,我认为我不需要第一部分:尝试删除分号以使其更具可读性(好吧,只是为了它)。它现在不会编译。编译器说它期望 a ;,计算a != b就好像它不在 for 循环中:“C4552:'!=':未使用表达式的结果”并最终得出结论:“C2143:语法错误:缺少 ';' 在 ')'" 之前

您不需要 init 语句,但确实需要分号。为什么我引用的这些资源最初没有明确说明这一点,或者以某种方式暗示我是盲目的?

Mik*_*CAT 5

分号是强制性的,因为init-statement包括分号。

N3337 6.5 迭代语句:

for (for-init-statement condition_{opt}; expression_{opt}) statement

for-init-statement:
    expression-statement
    simple-declaration
Run Code Online (Sandbox Code Playgroud)

6.2 表达式语句:

expression-statement:
    expression_{opt} ;
Run Code Online (Sandbox Code Playgroud)

7 声明:

simple-declaration:
    decl-specifier-seq_{opt} init-declaratior-list_{opt} ;
    attribute-specifier-seq decl-specifier-seq_{opt} init-declarator-list ;
Run Code Online (Sandbox Code Playgroud)