“for"循环后分号的影响 [英] Effect of semicolon after 'for' loop
问题描述
假设我想使用 for
循环在 C 中打印一条消息五次.为什么我在 for 循环后添加分号,如下所示:
Say I want to print a message in C five times using a for
loop. Why is it that if I add a semicolon after for loop like this:
for (i=0;i<5;i++);
消息没有打印 5 次,但如果我不把分号放在那里,它会打印吗?
the message does not get printed 5 times, but it does if I do not put the semicolon there?
推荐答案
分号是一个合法的声明,称为 null statement * ,意思是什么都不做".由于 for
循环执行单个操作(可能是包含在 {}
中的块)分号被视为循环的主体,从而导致您观察到的行为.
Semicolon is a legitimate statement called null statement * that means "do nothing". Since the for
loop executes a single operation (which could be a block enclosed in {}
) semicolon is treated as the body of the loop, resulting in the behavior that you observed.
以下代码
for (i=0;i<5;i++);
{
printf("hello
");
}
解释如下:
- 重复五次
for (i=0;i<5;i++)
- ...什么都不做(分号)
- 为局部变量打开一个新的作用域
{
- ...打印你好"
- 关闭作用域
}
如您所见,重复的操作是;
,而不是printf
.
* 参见 K&R,第 1.5.2 节
As you can see, the operation that gets repeated is ;
, not the printf
.
* See K&R, section 1.5.2
这篇关于“for"循环后分号的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!