Consider the following code:
#include<stdio.h>
int f()
{
printf(" hey ");
return 5;
}
int main()
{
printf("hello there %d",f(4,5));
f(4,5);
return 0;
}
I expected something like too many arguments to function ‘int f()’ but it gives an output even in strict C99 compilation. why is this behavior? But it seems like a C++ compiler gives an error.
C is much less strict than C++ in some regards.
A function signature f()
in C++ means a function without arguments, and a conforming compiler must enforce this. In C, by contrast, the behaviour is unspecified and compilers are not required to diagnose if a function is called with arguments even though it was defined without parameters. In practice, modern compilers should at least warn about the invalid usage.
Furthermore, in function prototype declarations (without definition) in C, empty parentheses mean that the parameters are unspecified. It can subsequently be defined with any number of arguments.
To prevent this, use the following prototypeISO/IEC 9899 6.7.6.3/10:
int f(void)
In addition to what Konrad wrote, C will also implicitly declare functions for you. For example:
int main(int argc, char** argv)
{
int* p = malloc(sizeof(int));
return 0;
}
will compile (maybe with a warning) without a #include <stdlib.h>
that contains the declaration.
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