I just noticed a behaviour with GCC that seems strange to me (not checked with other compilers).
If I compile this code :
#include <stdio.h>
void foo(int i)
{
printf("Hello %d\n",i);
}
int main(){
foo(1, 2);
return 0;
}
I will get a compiler error :
test.c:9:5: error: too many arguments to function ‘foo’
But if I compile this code :
#include <stdio.h>
void foo()
{
printf("Hello\n");
}
int main(){
foo(1, 2);
return 0;
}
I get no errors or warnings.
Could someone explain me why ?
I tested this with gcc 4.6.3 and arm-none-eabi-gcc 4.8.3
EDIT : I compile with all warnings : gcc -Wall test.c
In C, writing void foo()
means that foo takes an unspecified number of arguments.
To indicate that the function foo()
should take no arguments, you should write void foo(void)
For this reason you should also use the signature int main(void)
.
Turn on your warnings!
void foo()
is an old ANSI C way of declaring a function without a proper prototype. If you do this, the function acts sort of like void foo(...)
, and allows any number of arguments to be passed.
(In C++, void foo()
declares a null-arity function as you'd expect).
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