Why does omitting explicit 'int' type for a parameter fail to compile in gcc sometimes?

前端 未结 2 1741
予麋鹿
予麋鹿 2020-12-21 06:48

When declaring variables in C you can omit the type sometimes if you want to declare an int.

Why does omitting explicit \'int\' type for a parameter fai

相关标签:
2条回答
  • 2020-12-21 07:24

    The compiler is employing one of two grammars.

    When applying the K&R grammar, undeclared parameters are allowed, and default to ints.

    When applying the non-K&R grammar, all parameters must comply with the parameter declaration syntax i.e. declared with types and names.

    You invoke one or the other by choosing the corresponding declaration style.

    0 讨论(0)
  • 2020-12-21 07:27

    There are two forms of function definition in C: K&R style and the modern style with prototypes. You cannot mix them in a single definition.

    In K&R style (i.e., the style used in the 1978 first edition of Kernighan & Ritchie's "The C Programming Language", published 11 years before the first official ANSI standard for the language), you could write:

    /* Valid in K&R and 1989 ANSI C, invalid in C99 and later */
    main(argc, argv)    
    char *argv[];
    {
        /* . . . */
    }
    

    The stuff between the parentheses can only be a (possibly empty) sequence of identifiers, the names of the parameters. Between the ) and { you could optionally have a sequence of parameter declarations, specifying their types. If you omitted the type of a parameter, or of the function itself, it would default to int.

    The 1989 ANSI C standard kept this old form for backward compatibility, but declared it to be obsolescent. (Unfortunately, IMHO, it's remained that way even in the 2011 ISO C standard.)

    The 1999 ISO C standard dropped the "implicit int" rule, so even if, for some odd reason, you wanted to use an old-style definition, you'd still have to give all the types explicitly:

     /* Valid in all versions of C, but obsolescent */
    int main(argc, argv)
    int argc;
    char *argv[];
    {
        /* ... */
    }
    

    A modern prototype definition for main would be:

    /* Valid in 1989 ANSI C and later; write it this way! */
    int main(int argc, char *argv[]) { 
        /* ... */
    }
    

    You should always use prototypes; there is no good reason to write an old-style function definition (unless you're stuck using a very old compiler, but it has become very difficult even to find such a compiler).

    0 讨论(0)
提交回复
热议问题