I'm implementing some basic data structures in C and I found out that if I omit the return type from a function and call that function the compiler doesn't generate an error. I compiled with cc file.c
and didn't use -Wall
(so I missed the warning) but in other programming languages this is a serious error and the program won't compile.
Per Graham Borland's request, here's a simple example:
int test()
{
printf("Hi!");
}
int main()
{
test();
}
C is an old language and at the time it was introduced, returning integers was common enough to be the default return type of a function. People later started realizing that with more complicated return types, it was best to specify int to be sure you are not forgetting the return type, but in order to maintain backwards compatibility with old code, C could not remove this default behavior. Instead most compilers issue warnings.
If the function reaches the end without a return statement an undefined value is returned except in the main
function, 0 is returned. This has the same reason as above.
/* implicit declaration of printf as: int printf(int); */
/* implicit int type */
main()
{
printf("hello, world\n");
} /* implicit return 0; */
It's because in C, any variable / function is implicitly int
.
This is the same reason that you can use register
instead of register int
, or unsigned
instead of unsigned int
, auto
instead of auto int
, and static
instead of static int
. I personally always explicitly qualify my variables with int
, but whether you do or not is your option.
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