Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between main(void) and main() in C [duplicate]

Tags:

c

main

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()?

like image 407
Archit Avatar asked Sep 14 '10 16:09

Archit


People also ask

Is Main () and void main () the same 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().

What is the difference between main () and main void?

main() allows you to call main with any number of parameters. main(void) forces you to call main with no parameters.

Is it fine to write void main () or main () in C C++?

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.

Is void main correct in C?

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.


2 Answers

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.

like image 154
bmargulies Avatar answered Oct 23 '22 05:10

bmargulies


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.

like image 39
vanza Avatar answered Oct 23 '22 05:10

vanza