I was just writing a quick program for calculating some things when I came across the return statement/exit statement for the C program.
I declared main()
to be of type int
, so I would have to put in a return of an integer, or my program would not compile correctly. However, is it acceptable to make main
a Boolean
or even void
?
I know the standard way to create a C program is to return a value so any problems can be sorted out, among other things, but wouldn't a Boolean
work the same way? Also, could I get away with declaring it void
and not having problems with the operating system still running my program after it has been terminated?
Thanks for any and all help.
The C99 standard says: (§5.1.2.2.1 Program startup)
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent; or in some other implementation-defined manner.
So in a hosted environment, int
is the only valid, standard return type. Implementations can define other entry points though.
Note that section §5.1.2.2.3 Program Termination has this:
If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.
So you omitting a return from main
is legal in C99, as long as your main
returns an int
.
(But previous versions of the C standard didn't have that exception for main
- returning no value (or reaching the final }
without a return statement) causes "the termination status returned to the host environment [to be] undefined.".)