Why does declaring main as an array compile?

前端 未结 6 1932
一整个雨季
一整个雨季 2021-01-31 07:35

I saw a snippet of code on CodeGolf that\'s intended as a compiler bomb, where main is declared as a huge array. I tried the following (non-bomb) version:



        
6条回答
  •  伪装坚强ぢ
    2021-01-31 07:46

    The problem is that main is not a reserved identifier. The C standard only says that in hosted systems there is usually a function called main. But nothing in the standard prevents you from abusing the same identifier for other sinister purposes.

    GCC gives you a smug warning "main is usually a function", hinting that the use of the identifier main for other unrelated purposes isn't a brilliant idea.


    Silly example:

    #include 
    
    int main (void)
    {
      int main = 5;
      main:
    
      printf("%d\n", main);
      main--;
    
      if(main)
      {
        goto main;
      }
      else
      {
        int main (void);
        main();
      }
    }
    

    This program will repeatedly print the numbers 5,4,3,2,1 until it gets a stack overflow and crashes (don't try this at home). Unfortunately, the above program is a strictly conforming C program and the compiler can't stop you from writing it.

提交回复
热议问题