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



In C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return type of main is int, i.e. main() will return an integer value by default.

In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error. However, main() is used to denote the main function which takes no arguments and returns an integer data type.

The definition is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. for more.

void main(){
// Body
}

 A conforming implementation accepts the formats given below:

int main(){ 
// Body
}

and

int main(int argc, char* argv[]){
// Body
}

A conforming implementation may provide more versions of main(), but they must all have return type int. The int returned by main() is a way for a program to return a value to “the system” that invokes it. On systems that don’t provide such a facility the return value is ignored, but that doesn’t make “void main()” legal C++ or legal 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.

Example:

// CPP Program to demonstrate main() with
// return type
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    cout<< "This program returns the integer value 0\n";
}
Output
This program returns the integer value 0

NOTE: Neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to C89 and ARM C++, int is not assumed where a type is missing in a declaration. 

Consequently,

#include <iostream>
using namespace std;
 
main() // default return type of main in c++ is int
{
    // Body
      cout<<"This will return integer value.";
   
      return 0;
}

The above code has no error. If you write the whole error-free main() function without a return statement at the end then the compiler automatically adds a return statement with proper datatype at the end of the program. 

To summarize the above, it is never a good idea to use void main() or simply, main() as it doesn’t confirm standards. It may be allowed by some compilers though.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above