Reputation: 29
int func (int,int);
int main ()
{
printf("hello");
}
Consider the above function. What is the purpose of defining functions like func
? I have seen this repeatedly.
Upvotes: 0
Views: 205
Reputation: 802
This is just a function declaration of a function to tell compiler that a function with name func
exists having definition at end.
Consider this example:
#include<stdio.h>
int func (int,int);
int main()
{
printf("hello\n");
int c= func(5,4);
printf("%d\n",c);
}
int func(int a, int b)
{
return a+b;
}
Upvotes: 0
Reputation: 37227
All the other answers are not answering the correct question explicitly, so I'm adding one here.
First of all, it's not a function definition because the body is missing. This semantic is called function declaration.
Before calling a function, the compiler needs to know what exactly the function is. This is named a "prototype". A prototype must be known before generating correct code to call a function. Consider this code:
// No previous info
int a = func(1, 3);
The compiler doesn't know if it is calling int func(int, int)
or long func(char, double)
, nor can it perform error checking if the actual function is FILE* func(void*)
.
With a correct prototype privided, the compiler is able to perform necessary checking and generate the corresponding code of that function call.
Upvotes: 1
Reputation: 70911
int func(int, int);
does not define a function, but declares it by providing its prototype. It's the "promise" to the compiler, that latest the linker will provide a module exposing such a function.
The prototype for a function covers its:
The arguments' names are not relevant in the context of a declaration.
The function's arguments' names only need to be provided for the function's implementation, which might look like this:
int func(int a, int b)
{
return a + b;
}
On the other hand this
int func(int a, int)
{
return a;
}
is not valid.
The C Standard clearly states:
If the declarator includes a parameter type list, the declaration of each parameter shall include an identifier, except for the special case of a parameter list consisting of a single parameter of type void, in which case there shall not be an identifier. No declaration list shall follow.
Upvotes: 1
Reputation: 34588
It is not function defination but it is a functions declaration. A function declaration informs the compiler of the number of parameters the function has, the type of the function parameters and the type of the function return value.
1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the function.
5) It tells the name (identifier) of the function.
Upvotes: 0