Understanding Function Prototype in C

后端 未结 3 884
太阳男子
太阳男子 2021-01-21 05:07

Why does the following program works fine?

int main()
{
    int x;
    x = foo();
    printf(\"%d\",x);
    getchar();
    return 0;
}

int foo()
{
    return 2;         


        
相关标签:
3条回答
  • 2021-01-21 05:26

    Anything called as a function C is by default of type int, with no parameters (such as in your first case). If the compiler then finds a function which complies, there is no error.

    In the second case, the compiler compiles main() thinking the function is int, but then finds it's not true, and reports an error!

    COMMENT: Jonathan Leffler commented:

    Only in C89/C90. Not in C99; not in C11. Of course, some vendors still only implement C89; a notable example is Microsoft!

    0 讨论(0)
  • 2021-01-21 05:34

    Because of implicit function declaration, the compiler assumes that unspecified types are int by default.

    In the first case that is coincidentally true, but not in the second case.

    0 讨论(0)
  • 2021-01-21 05:39

    In C if a function is defined then its implicit return type is int.

    • In the first case the return type of the function is int so the main() recognizes the function and compiles without any errors.

    • In second case the return type of function is double so the main() fails to recognize the function thus generating an error so you need to declare the prototype of function.

    Also in older versions up till C89 if the return type is not mentioned then its is implicitly considered as int.

    In C99 standard doesn’t allow return type to be omitted even if return type is int.

    For more details you can check: implicit return type C

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