Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int main() vs void main() in C [duplicate]

Tags:

c

main

int

void

In C, I know that int main() returns an int where void main() does not. Other than that, is there a difference between them? Is the first better than the second?

like image 771
madU Avatar asked Feb 20 '12 05:02

madU


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 int main () and int main void?

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.

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.

Why void main is not used in C?

The reason not to use void main() is that the language standard doesn't permit it, any more than it permits double main(long long foo, time_t bar) .


2 Answers

The overwhelming majority of the time, one of int main(void) or int main(int argc, char* argv[]) is what you need to use. In particular, if you're writing a program that's going to be compiled by any major compiler for running on a personal computer, with the full set of the C standard libraries, then you almost certainly need to be returning an int from main.

(I would also avoid using an empty argument list, see "Why don't we use (void) in main?")

The C99 standard does allow for other implementation-defined signatures, and you can use these if you've read the manual for your compiler and it says you can.

(5.1.2.2.1) It shall be defined with a return type of int and with no parameters ... or with two parameters ... or in some other implementation-defined manner

Personally I would avoid them even if they are allowed (if possible), because it's one more thing to worry about if you ever need to port to another system.

See the comments below "Why don't we use (void) in main?" for some interesting discussion on this.

like image 171
detly Avatar answered Oct 12 '22 03:10

detly


If your book says void main() it is either very very out of date, was written by an idiot (or both)

edit: OK unless you are in a very unlikely system where you have a freestanding main - see Why is the type of the main function in C and c++ left to the user to define?

like image 39
Martin Beckett Avatar answered Oct 12 '22 02:10

Martin Beckett