Can anyone tell me the difference between int main()
and int main(void)
? Why do both of them work and what is the default argument to int main()
?
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().
main() allows you to call main with any number of parameters. main(void) forces you to call main with no parameters.
Note: Even if your compiler accepts void main() avoid it, or risk being considered ignorant by C and C++ programmers. In C++, main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution.
No. It's non-standard. The standard prototype of main is int main() with the optional command line arguments argc and argv . The int returned by main() is a way for a program to return a value to the system that invokes it.
No difference under ordinary circumstances. This is no 'default argument to main()', since it has no arguments at all.
Here's the un-ordinary circumstance. If you write your own call to main, then ()
will permit you to pass it any parameters you like, while (void)
will force you to pass it none. Still, none of this matters in terms of the 99.99999999% case, which is main being invoked by the runtime to launch your program. The runtime neither knows nor cares if you write ()
or (void)
.
If you code the standard int main(int argc, char **argv)
you will get your command-line parameters in there.
main()
allows you to call main with any number of parameters. main(void)
forces you to call main with no parameters. So:
main(foo, bar);
Is fine with main()
but not with main(void)
- the compiler generates an error.
Now if you're specifically asking about the program's entry point, it doesn't really make a difference; in either case, you won't have the arguments to the program (argc, argv, envp) available.
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