Many are familiar with the hello world program in C:
#include <stdio.h>
main ()
{
printf ("hello world");
return 0;
}
Why do some precede the main() function with int as in:
int main()
Also, I’ve seen the word void entered inside the () as in:
int main(void)
It seems like extra typing for nothing, but maybe it’s a best practice that pays dividends in other situations?
Also, why precede main() with an int if you’re returning a character string? If anything, one would expect:
char main(void)
I’m also foggy about why we return 0 at the end of the function.
The following has been valid in C89
But in modern C (C99), this isn’t allowed anymore because you need to explicitly tell the type of variables and return type of functions, so it becomes
Also, it’s legal to omit the
return 0in modern C, so it is legal to writeAnd the behavior is as if it returned 0.
People put
voidbetween the parentheses because it ensures proper typechecking for function calls. An empty set of parentheses in C mean that no information about the amount and type of the parameters are exposed outside of the function, and the caller has to exactly know these.The call to
fcauses undefined behavior, because the compiler can’t verify the type of the argument against whatfexpects in the other modules. If you were to write it withvoidor withint, the compiler would knowSo for
mainit’s just a good habit to putvoidthere since it’s good to do it elsewhere. In C you are allowed to recursively callmainin which case such differences may even matter.Sadly, only a few compilers support modern C, so on many C compilers you may still get warnings for using modern C features.
Also, you may see programs to declare
mainto return different things thanint. Such programs can do that if they use a freestanding C implementation. Such C implementations do not impose any restrictions onmainsince they don’t even know or require such a function in the first place. But to have a common and portable interface to the program’s entry point, the C specification requires strictly conforming programs to declare main with return typeint, and require hosted C implementations to accept such programs.