C function definition and declaration

2019-09-01 18:55发布

问题:

I'm a Java programmer,I learnt a little C++ and now I'm studying a little C for my job. I can't understand C behaviour about function declaration/definition and related function calls. From K&R I know that in C (very different from C++) I can call a function that has not been previously declared,and the compiler assumes an implicit declaration of the type:

int main() 
{
  function(10);   // implicit function declaration ( int function() )
}

and I know that such a declaration implies a function that accepts a fixed but indefinite number of arguments of any type (as long as each call is consistent with the others). And I know this is K&R C, before C89, but I want to know how it works as well. Now, I have this test code, I can't understand:

#include <stdio.h>

function();

int main()
{
  printf("hello %d",function(1,2,3));
  implicit(11,12,32);     // implicit function declaration ( implicit() )
}


int implicit(int b)
{

}

function(int a)
{

}

in the case of function the declaration (return type is assumed to be int,no assumption about the arguments) does match the definition (the compiler issues a warning) but if I call the function with the wrong arguments,it compiles! Same for the function implicit. I can't understand..

回答1:

The thing you have to remember is that the compile is pretty much sequential when it comes to declarations and definition. When the compiler processes the call for function all it has is the declaration that, as you say, doesn't have any assumptions about the arguments, which means you can call the function with any argument you like. When the compiler sees the definition, it doesn't go back to issue an error about the call, it might issue a warning though.

As for the implicit function, when the compiler first sees it it will assume that the arguments are what you pass in the call when it deduces the declaration. Again it will not know anything else until it later sees the declaration, and may issue a warning then.

Calling a function with to many, or to few, arguments leads to undefined behavior, which is why implicitly declared functions are so dangerous, as well as using an empty argument list when declaring functions.



回答2:

There is really nothing to understand. This is a legacy C behaviour, which was an extremely lax language. As long as compiler could generate assembly instruction, it would gladly compile your code, and leave it to you to clean up the mess.

This is why it compiles in your case. Compiler can generate instruction to call the function - so it does as asked.