Why is adding a return statement for the main()
function in C important if the programs I make runs the same without it?
Is there a disadvantage in my programs if I omitted the return statement in the main()
function?
Why is adding a return statement for the main()
function in C important if the programs I make runs the same without it?
Is there a disadvantage in my programs if I omitted the return statement in the main()
function?
It is by convention that you tell the operating system if your program exited successfully(return
ing 0), or if there was an error(for example, by return
ing an error code).
To remain more standards compliant, use return EXIT_SUCCESS
or return EXIT_FAILURE
.
If you want your code to be legal (i.e. works on all compilers that support the standard), then if you've defined main
as:
int main() {
return 0;
}
It should return an integer. In this case, 0. Why? Because according to the standard, if you've defined a function to have a certain return type, it should return that return type. Otherwise, it just isn't legal.
It may compile (thanks to forgiving compilers, and hence this should not be relied upon), but that doesn't mean it's correct.
The ISO C++ Standard (ISO/IEC 14882:1998) specifically requires main to return int. It has an explicit "shall" constraint upon well-formed programs. It shall have a return type of int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { /* … */ }
int main(int argc, char* argv[]) { /* … */ }
But the ISO C Standard (ISO/IEC 9899:1999) actually does not mandate this as the C++ standard does. This comes as a surprise to many people. But despite what many documents say, including the Usenet comp.lang.c FAQ document (at great length), the actual text of the C Standard allows for main returning other types.
You can use either the int
or void
. Though, it is better to use the int
returning because you should inform the OS how your program exited. See a practical example:
int main() {
int a;
printf("Enter a positive number: "); scanf("%d", &a);
if(a<0) return 1;
return 0;
}
I am not sure if it is the best example, but it could help you understand the concept better. Hope that helps!