This question already has an answer here:
- What should main() return in C and C++? 18 answers
I get this code:
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
char *ptr = (char*)malloc(10);
if(NULL == ptr)
{
printf("\n Malloc failed \n");
return;
}
else
{
// Do some processing
free(ptr);
}
return;
}
It compiles successfully in Visual C, but do not compile in gcc, I get "error:'main' must return 'int'". So is the return type 'int' of main() function is a convention(which is for compiler to define), or a rule of C?
The C standard (ISO/IEC 9899:2011) says:
Thus, the only portable declaration for
main()
has a return type ofint
. If MSVC defines thatvoid
is permitted ('or in some other implementation-defined manner'), so be it, but do not expect the code to be portable. The old versions of the Microsoft compilers (up to and including MSVC 2005) do not permitvoid main()
: see the documentation atmain
: Program startup and Themain
Function and Program Execution. However, MSVC 2008 and later are documented to allowvoid main()
: seemain
: Program Startup. The three-argument form ofmain()
is noted as a common extension in Appendix J:The value returned from
main()
is transmitted to the 'environment' in an implementation-defined way.Note that
0
is mandated as 'success'. You can useEXIT_FAILURE
andEXIT_SUCCESS
from<stdlib.h>
if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.According to c standard
main()
should return integer for informing success or failure.Generally for success it returns zero and for failure it returns a integer value(either positive or negative). Generally main is declared asso it expects integer as return type.
If command line arguments are there,
void main()
is non-standard C andint main()
is the standard.