In the following program,I use two functions prd() and display().I have declared neither of them ahead of main() before invoking them in main(),and I have defined both after main().Yet while prd() works smoothly inside main(),invoking display() shows the warning " previous implicit declaration of 'display' was here ".What is different about display() that there is a warning for it but not for the other funciton prd()?I have declared neither of them to begin with.Still there is warning due to invocation of one, but other one works fine.
#include<stdio.h>
int main()
{
int x=8,y=11;
printf("The product of %d & %d is %d",x,y,prd(x,y));
display();
return 0;
}
int prd(int x,int y)
{
return x*y;
}
void display()
{
printf("\n Good Morning");
}
PS: And I would really appreciate if you can answer this secondary question --"Is function declaration not necessary at all in C provided there is a definition for it?".I have the habit of declaring all functions of the program before the main() function, and then defining them after the main() function.Am I wrong?
Function declarations are important because a calling convention (part of the ABI of a platform) can define different places for arguments and return values based on the types a function returns and accepts as arguments.
implicit declaration of function means that you are trying to use a function that has not been declared. In our example above, StartBenchmark is the function that is implicitly declared.
You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files. But you can't call main in C++ so you don't need one.
You can declare a function as an explicitly defaulted function only if the function is a special member function and has no default arguments. For example: class B { public: int func() = default; // Error, func is not a special member function.
When you use undeclared display()
the compiler implicitly declares it as if it were returning int
.
When the compiler finally sees the definition of display()
, it sees that the return type is void
, but it's already assumed it be int
and so the definition and the implicit declaration differ, hence the error/warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With