cintegerprogram-entry-point

In C programming language, can the main function begin with main() instead of int main()?


I'm reading the "C Programming Language, 2nd edition" by Dennis Ritchie and Brian W.Kernighan. On page 38, the main body of the program begins with main() instead of int main(), I believe that's an error. But I'm a novice programmer. Are there any special conditions or cases for which you doesn't have to mention the type int in front of the main function?

I tried without mentioning int and the compiler didn't execute.


Solution

  • The earliest versions of C (up to C99) allowed an "implicit int" definition; functions that didn't have an explicit type were assumed to return int. K&R C didn't even have function prototype syntax, so function definitions with parameters looked like this:

    /**  
     * Return type is assumed to be int
     *
     * Parameter list only contains the names of the parameters;
     * types must be specified in a separate declaration
     */
    foo(x, y) 
      int x;
      int y;
    {
      return x*y;
    }
    

    So yeah, in a lot of very old C code (1970s through the late 1980s), you'll see main defined as

    main()
    {
      ...
    }
    

    or

    main(argc, argv)
      int argc;
      char **argv;
    {
      ...
    }
    

    Practice since C89 is to use prototype syntax, and again implicit int is no longer allowed since C99, so main should be defined as

    int main( void )
    {
      ...
    }
    

    or

    int main( int argc, char **argv )
    {
      ...
    }