Saturday, October 5, 2013

What is the return value of the main() function in C?

As per standard C , main() function always returns int. mostly zero if it is success and error code if it fails. some compilers accepts void as a return type for main() function. But standard compilers like gcc will give you the warning at the time of compilation saying that void is not allowed as a return type for the main() function.

#include<stdio.h>
void main()
{
        printf("testing return type for main");
}

Below is the warning message you will get when compiling using GCC for the above sample code:

$ gcc main.c
main.c: In function ‘main’:
main.c:3: warning: return type of ‘main’ is not ‘int’


Why main() returns int: In C , main() is the  user entry point to execute the code, so whatever writing the code in main, it is user specified code. But internally C execute many functions before and after the main function to startup and exit the program/application.  So when exiting C program, it calls exit() function and it internally calls _exit() function to exit the program. This exit process, specifies whether exit process completed successfully or any failure occurred due to some reason. If success it returns zero and if it fails it will return error code which is generally a numeric value. so logically it should return integer.

No comments:

Popular Posts