1
{
 static int i=5;
 if(--i)
  {
   main(); 
   printf("%d ",i);
  }
}

这个程序的输出是0 0 0 0

这个程序不应该显示编译器错误吗?我在这里想念什么?

4

2 回答 2

0

First of all, I +1 your question because in my 15 years of programming I have never thought of recursively calling main()!

Now regarding your question, it compiles because main() is just a function like any other function in the code. The only special thing about it is that the linker expects to see a main() in the code and a call to main() is automatically inserted inside the executable. (I think you can even use linker switches to define a different startup function name).

But other than that, it's a normal function.

于 2013-08-29T18:58:37.317 回答
0

这没有什么特别的main,意味着你不能在你的程序中使用它,但不推荐这样做,因为它会混淆你的代码。(这个因难以阅读而赢得比赛的可怕代码称它为自己的主要代码,并且它在没有警告的情况下编译:http ://research.microsoft.com/en-us/um/people/tball/papers/xmasgift/ )

如果您对程序的流程感到困惑,请考虑main切换printf

#include <stdio.h>
void main()
{
  static int i=5;
  if(--i)
  {
    printf("%d ",i);
    main(); 
  }    
}

输出是4 3 2 1

编辑:此代码正确使用int main(void)

#include <stdio.h>
int main(void)
{
  static int i=5;
  if(--i)
  {
    printf("%d ",i);
    main(); 
  }

  return 0    
}
于 2013-08-29T18:59:13.360 回答