C/Return type of main()
Expert: Prince M. Premnath - 8/26/2009
QuestionIn college, I've gotten used to programming using only
main() {
//code
}
Last month I underwent a training and was reminded that it's actually
int main() {
//code
}
Both function as if there's no difference at all. But I do believe there is. What is it? Also, the latter needs to add a return statement before the closing brace, right?
AnswerHi dear Nelson!
By default all the function defined in C program will have the return type is of int and not void
eg if you define a function sample as
sample() /* function defined without specifying any return type */
{
.
.
.
}
Compiler will mark this function as "function sample() should will return a int value" ie if you don't want a function to return any value please specify "void" in the return type for all the function you doesn't want to return any value as
void sample()
{
..
..
}
lets get back to main() , perhaps main() is also a userdefined function with little bit extra features so it should also be qualified with the return type if you use main(), the compiler will insert the defaults and note it as int main()
eg
#include <stdio.h>
main(){ /* by default assumed integer return type */
printf("Hi There");
return 0; /* Integer value should be returned */
}
Whats is this "return 0;" is all about ??
Its common for a program to return a status code after the execution to the operating system.
which will enable the operating system to keep track on the status of the program. this couls be done in a C program by two way's
using main() and exit() function ,
There are three and only three completely standard and portable values to return from main() or pass to exit():
The plain old ordinary integer value 0 ( which is equvalent to EXIT_SUCCESS)
The constant EXIT_SUCCESS defined in <stdlib.h> or <cstdlib> ( which is equvalent to 0)
The constant EXIT_FAILURE defined in <stdlib.h> or <cstdlib> ( which is equvalent to 1)
If you use 0 or EXIT_SUCCESS your compiler's run time library is guaranteed to translate this into a result code which your operating system considers as successful.
If you use EXIT_FAILURE your compiler's run time library is guaranteed to translate this into a result code which your operating system considers as unsuccessful.
ive answered similar question
kindly follow the link
http://en.allexperts.com/q/C-1587/return-type-main.htm
get back to me for more quries !
Thanks and Regards!
Prince M. Premnath