Declaration and prototype difference

前端 未结 4 2134
盖世英雄少女心
盖世英雄少女心 2021-02-07 11:45

What is the difference between declaration and prototype in C? In which situations they are called declarations and in which prototypes?

4条回答
  •  抹茶落季
    2021-02-07 12:49

    A declaration introduces a name:

    int a;    // "a" has type int
    

    A function declaration (that is not also a prototype) only introduces the name of a function and its return type:

    int f();   // a function call expression "f(x, y, ...)" has type int
    

    However, such a function declaration does not specify which arguments are valid for the function call; in other words, it does not specify the function signature. This is done by a function prototype (which is a kind of declaration):

    int g1(void);         // "g1" takes no arguments, "g()" has type int
    int g2(float, char);  // "g2" takes two arguments
    int g3(int, ...);     // "g3" takes at least one argument
    

    Whether a function prototype is visible at the time of a function call has important consequences on the call arguments: If no prototype is visible, all arguments undergo default argument promotions. By contrast, if a prototype is available, function arguments are converted to the types of the corresponding formal parameters (and the program is ill-formed if the number of arguments doesn't match or if any of the conversions would be ill-formed).

    To explore this further, observe that there are certain "impossible" combinations: If we had a declaration int g2(); and a definition int g2(float, char) { return 0; }, it would never be possible to call g2 just with the declaration, because the formal parameter types cannot result from default argument promotions. It is generally advisable to always use prototype declarations and never use non-prototype declarations.

    Finally, it is possible to call a prototyped function with more arguments than it has parameters, if the prototype ends in the ellipsis (...). The use of to get at those arguments requires that a function prototype is visible at the time of call for such a variable-argument function.

提交回复
热议问题