Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between void main and int main in C/C++? [duplicate]

Does it matter which way I declare the main function in a C++ (or C) program?

like image 654
Kredns Avatar asked Mar 11 '09 23:03

Kredns


People also ask

What is difference between main and int main and void 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().

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.

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

In that case, the value returned is 0, meaning successful execution. is an error because the return type of main() is missing. It is never a good idea to use “void main()” or just “main()” as it doesn't confirm standards.

Can we use main () instead of int main ()?

It is okay to use main() instead of int main() in C but this is an outdated practice.


2 Answers

The difference is one is the correct way to define main, and the other is not.

And yes, it does matter. Either

int main(int argc, char** argv) 

or

int main() 

are the proper definition of your main per the C++ spec.

void main(int argc, char** argv)

is not and was, IIRC, a perversity that came with older Microsoft's C++ compilers.

https://isocpp.org/wiki/faq/newbie#main-returns-int

like image 157
Alan Avatar answered Sep 30 '22 15:09

Alan


Bjarne Stroustrup made this quite clear:

The definition void main() is not and never has been C++, nor has it even been C.

See reference.

like image 41
vobject Avatar answered Sep 30 '22 16:09

vobject