Understanding the Prototype function in C

Why does the program work fine?

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

int foo()
{
    return 2;
}

      

and not this program?

//double function(void);

int main(){
    double val;
    val = function();
    printf("%ul\n",val);
}

double function(void){
    double num;
    num = DBL_MAX;
    printf("%ul\n",num);
    return num;
}

      

In my understanding, the definition of functions in both of these cases is missing before main()

. So why in the first case the function is called anyway, even if the compiler doesn't have a definition of it before main()

and not in the second case?

+3


source to share


3 answers


Because of the implicit declaration of the function, the compiler assumes that no types are specified by default int

.



In the first case, this match is true, but not in the second case.

+7


source


Anything called a C function is int by default, with no parameters (like in your first case). If the compiler then finds a function that matches, there is no error.

In the second case, the compiler compiles main (), assuming that the function is an int, but then finds that this is 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 use C89; Microsoft is a notable example!

+6


source


In C, unless the function is defined, then its implicit return type int

.

  • In the first case, the return type of the function int

    , therefore, main()

    recognizes the function and compiles without any errors.

  • In the second case, the return type of the function double

    , therefore, main()

    cannot recognize the function, thus generating an error, so you need to declare the function prototype.

Also in older versions up to C89, if no return type is specified, it is implicitly treated as int

.

The C99 standard does not specify the return type, even if the return type int

.

For more information, you can check: C implicit return type

+1


source







All Articles