'for'循环后分号的影响 [英] Effect of semicolon after 'for' loop

查看:151
本文介绍了'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?

推荐答案

分号是所谓合法声明的空语句 * ,表示什么都不做。因为循环执行一个单一的操作(这可能是块放在 {} )分号被视为循环体,导致在你所观察到的行为。

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.

以下code

 for (i=0;i<5;i++);
 {
     printf("hello\n");
 }

是国际preTED如下:

is interpreted as follows:


  • 重复五次为(i = 0;我小于5;我++)

  • ...什么都不做(分号)

  • 打开局部变量新的作用域 {

  • ...打印你好

  • 关闭范围}

  • Repeat five times for (i=0;i<5;i++)
  • ... do nothing (semicolon)
  • Open a new scope for local variables {
  • ... Print "hello"
  • Close the scope }

正如你所看到的,是被重复操作; ,而不是的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆