Void Main(), Main() and Int Main() in C/C++

Like any other function, the main is also a function but with a special characteristic that the program execution always starts from the main. So the function main needs arguments and a return type. These int and void are its return type. Void means it will not return any value, which is also ok. But if want to know whether the program has terminated successfully or not, we need a return value that can be zero or a non-zero value. Hence the function becomes int main() and is recommended over void main().

void main() { /*...*/ }

If we’re declaring main this way, stop. The definition void main() is not and never has been C++, nor has it even been C. Avoid using it Even if your compiler accepts “void main()”, or risk being considered ignorant by C and C++ programmers.

main() { /*...*/ }

It is acceptable in C89; the return type, which is not specified, defaults to int. However, this is no longer allowed in C99. main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution. This type of declaration is an error because the return type of main() is missing. main(){/*…*/} is probably never a good idea.

int main() { /*...*/ }

This is the best way to write main if we don’t care about the program arguments. If we care about program arguments, we need to declare the argc and argv parameters too. We should always define main in this way. Omitting the return type offers no advantage in C89 and will break your code in C99.

The correct signature of the function is: 

int main(int argc, char **argv)

The name of the variable argc stands for “argument count”; argc contains the number of arguments passed to the program. The name of the variable argv stands for “argument vector”.

When we return 0 at the end ( while using int as the return type) it tells the OS that the program is functional and is without any error(except logical error), as the main function is called by OS and it returns 0 to the OS.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Reply