Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In C/C++ the default return type of the main function is int, i.e. main() will return an integer value by default. The return value of the main tells the status of the execution of the program. The main() function returns 0 after the successful execution of the program otherwise it returns a non-zero value.

Using void main in C/C++ is considered non-standard and incorrect. void main() in C/C++ has no defined(legit) usage, and it can behave unexpectedly or sometimes throw garbage results or an error.

However some compilers may support void main() or main() without parameters, it is not considered good practice and can lead to unexpected behavior of the code when run on other platforms. This definition is not and never has been in C++, nor has it even been in C.

Below is the incorrect implementation of the main function:

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 using it, or risk being considered ignorant by C and C++ programmers. In C++, main() does not need to contain an explicit return statement. In that case, the value returned is 0, meaning successful execution.

Example

C++




// 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. In contrast to C89 and ARM C++, int is assumed where a type is missing in a declaration.

Consequently,

C++




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


Output

This will return integer value.

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.

Conclusion

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



Last Updated : 27 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads