Frage

I found here that function prototype is necessary before function call if the function is below function calling.

I checked this case in gcc compiler and it compile code without function prototype.

Example:

#include <stdio.h>

//int sum (int, int); -- it runs with this commented line

int main (void)
{
   int total;       
   total = sum (2, 3);
   printf ("Total is %d\n", total);        
   return 0;
}

int sum (int a, int b)
{
   return a + b;
}

Could explain somebody this issue?

War es hilfreich?

Lösung

When you don't provide a function prototype before it is called, the compiler assumes that the function is defined somewhere which will be linked against its definition during the linking phase. The default return type is assumed to be int and nothing is assumed about the function parameter. This is called implicit declaration. This means that the assumed function signature here is

int sum();

Here, the empty parameter list means the function sum takes a fixed but unknown number of arguments all of which are of unknown types. It is different from the function declaration

int sum(void);

However, in C++, the above two declarations are exactly the same. If your function has a return type other than int, then the assumed function signature won't match and this will result in compile error. In fact, it's an error in C99 and C11. You should always provide function prototype before it is called.

Andere Tipps

It says on this page that: " You don't have to declare the function first, but if you don't, the C compiler will assume the function returns an int (even if the real function, defined later, doesn't)."

It is confirmed here.

As for arguments: "and nothing is assumed about its arguments."

I changed your code to #include

/* int sum (int, int); -- it runs with this commented line */

int
main (void)
{
    int total;

    total = sum (2, 3);
    printf ("Total is %d\n", total);

    return 0;
}

int
sum (int a, int b)
{
    return a + b;
}

Then compile with:

gcc --std=c90 -ansi -pedantic node.c

Also i try with some standard but may be it's related to gcc version and C standard.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top