-1

我对 C 语言中的 for 循环问题感到困扰。

当我写:

#include<conio.h>
#include<stdio.h>
main()
{
    int i = 0;
    for( ; i ; )
    {
        printf("In for Loop");
    }
    getch();
}

输出:没有打印。

代码被执行,但 printf 语句由于条件而没有打印。好的,这里没问题。

但是当我写这段代码时:

#include<conio.h>
#include<stdio.h>
main()
{
    for( ; 0 ; )
    {
        printf("In for Loop");
    }
    getch();
}

输出:在 for 循环中。

我的 for 循环被执行了 1 次,但实际上它一定不能被执行。我不知道为什么?stackoverflow的编码器/程序员/黑客可以帮助我吗?请解释一下为什么我的 for 循环只给出一次这个输出。

4

3 回答 3

12

你写的不应该打印任何东西,但我怀疑导致问题的实际第二种情况代码(不是你输入的)是:

for( ; 0 ; );     // <==== note the trailing semicolon there.
{
    printf("In for Loop");
}

在这种情况下 for 循环不会执行空语句,然后{ }代码会执行一次。

编辑:如果这不是问题,请将显示问题的完整程序直接粘贴到您的问题中。

编辑2:

以下最小可编译示例不打印任何内容:

#include <cstdio>

int main()
{
    for( ; 0 ; )
    {
        std::printf("In for Loop");
    }
}
于 2012-08-07T14:47:49.637 回答
1

两种方式都不应该输出任何东西。

于 2012-08-07T14:48:23.513 回答
0

我无法在我的机器上复制这种行为,用 gcc 编译。这两个程序是:

#include <iostream>
int main()
{
  for( ; 0 ; )
  {
    std::cout << "Here I am!";
  }
  std::cout << "End of the program.";
}

输出

End of Program

一样

#include <iostream>
int main()
{
  int i = 0;
  for( ; i ; )
  {
    std::cout << "Here I am!";
  }
  std::cout << "End of Program";
}

这是我们期望发生的,因为读取为循环继续条件的 0 被评估为 false,因此永远不会进入循环。

于 2012-08-07T15:10:42.527 回答