Mr *_*rte 1 c grammar for-loop token
我的程序中有这个代码:
if (primeiro != atual){
for (i = 0; i < atual -> numeroChaves; i++)
// comment
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
d8641900: In function 'printaArvore':
d8641900:130:7: error: expected expression before '}' token
}
^
Run Code Online (Sandbox Code Playgroud)
所以我在代码中做了以下更改:
if (primeiro != atual){
for (i = 0; i < atual -> numeroChaves; i++){}
// comment
}
Run Code Online (Sandbox Code Playgroud)
它运行顺利.
我的疑问是:我的代码有问题,还是在所有情况下都适用规则?
有趣的是,在我的代码的其他部分,我有类似的情况(在for循环后没有"{}"),但在它之后我有一个有效命令的行,它运行完美.
Nae*_*mul 12
C中的"for"循环需要一个语句.
如果您需要多个语句,则可以用{和将它们括起来}.
(当然,您也可以附上零或一个语句.)
并且;可以代表一个空洞的陈述.
所以以下任何一个都是正确的.
for (int i=0; i<10; i++);
for (int i=0; i<10; i++) {}
for (int i=0; i<10; i++) function_that_do_nothing();
for (int i=0; i<10; i++) 1;
for (int i=0; i<10; i++) function_that_do_something();
for (int i=0; i<10; i++) just_a_statement;
for (int i=0; i<10; i++) { statements... }
Run Code Online (Sandbox Code Playgroud)
另外,
for (initialization; condition; statement)
one_statement;
Run Code Online (Sandbox Code Playgroud)
不能分开,所以以下是平等的.
for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
a_statement;
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++)
a_statement;
}
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
a_statement;
}
}
Run Code Online (Sandbox Code Playgroud)
同样的事情if或者while.