This question already has an answer here:
- What should main() return in C and C++? 18 answers
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()
?
This question already has an answer here:
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()
?
main()
allows you to call main with any number of parameters.main(void)
forces you to call main with no parameters. So:Is fine with
main()
but not withmain(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.
From a practical viewpoint, there's no real difference. With
int main(void)
, you're explicitly stating thatmain
takes no parameters, so you can't invoke it with any. Withint main()
, you're leaving open the possibility of invokingmain
with some parameters.However, except in strange situations like code golf or intentionally obfuscated code, you don't invoke
main
anyway -- it's the entry point to the program, so it's automatically invoked by the startup code. The startup code will pass the command line arguments anyway, so your choices don't change how it's invoked, only whether you use or ignore the parameters that get passed.The standard does specifically allow you to define
main
with or without parameters (§5.1.2.2.1/1):Though it's outside the tags specified, in C++ the situation is slightly different. In C, a function declaration like:
specifies that
f
is a function returning anint
, but gives no information about the number or type of parametersf
might expect (this is included primarily for compatibility with old code -- at one time, this was the only way to declare a function in C). In C++, that same declaration explicitly declaresf
as a function that takes no parameters, so attempting to invokef
with one or more parameters cannot invoke this function (it must either invoke another overload or produce an error if no suitable overload is found).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.