What is the difference between the definitions "int main (void)" and "int main (int argc, char *argv)" and when to use which?
As per the current standard and cppreference these two are the correct way to define the
main() function. I know what the parameters mean in either definition, and am not seeking clarifications on that aspect. What I'd like to understand is:
- When to use
int main (void)v/s
int main (int argc, char *argv).
- Hypothetically, when the program doesn't expect command-line arguments, is there any difference to the compiler (let's say
clang) at all?
- (Just for the sake of writing self-documenting code) should I use
int main (void)when the program doesn't expect command line arguments and
int main (int argc, char *argv)when it does?
I think you can get a good answer here. Reading this article, my answers to your questions are:
int main (int argc, char *argv)whenever you need to access the program's arguments;
- I do not expect to be any difference to the compiler in both ways, once, in this experiment, both C programs had the same assembly output;
- I recommend you to use
int main (void)whenever your program does not need to access the arguments. This way, it is clear for other people that your program do not use them. In future, if you need to access the program's arguments, changing the syntax of the
main()function is not that hard.