Why do we need to use int main
and not void main
in C++?
The void main() indicates that the main() function will not return any value, but the int main() indicates that the main() can return integer type data. When our program is simple, and it is not going to terminate before reaching the last line of the code, or the code is error free, then we can use the void main().
In C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return type of main is int, i.e. main() will return an integer value by default. In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error.
int main represents that the function returns some integer even '0' at the end of the program execution. '0' represents the successful execution of a program. int main(void) represents that the function takes NO argument. Suppose, if we don't keep void in the bracket, the function will take any number of arguments.
In that case, the value returned is 0, meaning successful execution. is an error because the return type of main() is missing. It is never a good idea to use “void main()” or just “main()” as it doesn't confirm standards.
The short answer, is because the C++ standard requires main()
to return int
.
As you probably know, the return value from the main()
function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished. Returning a value from main()
provides one way for the programmer to specify this value.
Most Operating Systems report back to the user, or the calling process, if an application was successful or not. This is especially useful in scripting, where the script can conditionally branch (if-then) on the results of a program. Something along the lines of:
// pseudo-code screenscrape http://mydatasource.com > results.txt if errorlevel == 0 then processfile results.txt else echo Screen Scraping Failed! end if
This result status is done via the return value of main.
While some compilers allow for void main, for the sake of consistency and simplicity, the ANSI standard requires one single prototype of main:
int main(int argc, char *argv[]);
Because in C, arguments are cleaned up by the caller, the author of main can neglect to declare or process the arguments argc & argv. However, if the setup-routines that call main expect an int return value, and instead don't find one, behavior can undefined.
Short answer:
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