I have a simple code, where my functions are declared before main function like that:
int function1();
int function2();
int main() {
/* ... */
function1(x,y);
function2(x,y);
/* .... */
}
int function1(int x, float y) { /* ... */ }
int function2(int x, float y) { /* ... */ }
And after my main function I have definitions of functions:
Is there some difference, when I declare functions before main like this?
int function1(int x, float y);
int function2(int x, float y);
int main() {
/* ... */
function1(x,y);
function2(x,y);
/* .... */
}
int function1(int x, float y) { /* ... */ }
int function2(int x, float y) { /* ... */ }
Yes, they are different.
In the first example, you are just telling the compiler about the name and return type of the function and nothing of its expected arguments.
In the second example you are telling the compiler the full signature of the functions, both return type and expected arguments, prior to calling them.
The second form is pretty much universally better as it helps you compiler do a better job warning you when you have the wrong type or number of arguments when calling the function.
Also note int function()
in C is a function that can accept any arguments, not a function that accepts no arguments. For that you need an explicit void
, i.e int function(void)
. This mostly trips up those coming to C
from C++
.
See also: Why does a function with no parameters (compared to the actual function definition) compile?
To demonstrate why the first, antiquated form is bad in modern C, the following program compiles without warning with gcc -Wall -ansi -pedantic
or gcc -Wall -std=c11
.
#include<stdio.h>
int foo();
int main(int argc, char**argv)
{
printf("%d\n", foo(100));
printf("%d\n", foo(100,"bar"));
printf("%d\n", foo(100,'a', NULL));
return 0;
}
int foo(int x, int y)
{
return 10;
}
UPDATE: M&M brought to my attention that my example uses int
not float
for the functions. I think we can all agree that declaring int function1()
is bad form, but my statement that this declaration accepts any arguments is not quite correct. See Vlad's answer for relevant spec section explaining why that is the case.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments