Should main() always return a value?
Yes, unless it calls exit().
When a program runs, it usually terminates with some indication of success or some error code. A C program controls this indication in one (or both) of two ways, which have exactly the same effect:
When a program runs, it usually terminates with some indication of success or some error code. A C program controls this indication in one (or both) of two ways, which have exactly the same effect:
It returns a value (the success or failure code) from main().
It calls exit(), passing the success or failure code as an argument.
If the program “drops off the end of main()” without taking either of these actions, there’s no guarantee whatthe success or failure code will be. This is a Bad Thing.
Whenever you write a C program, quickly check the main() function. The last statement should always be either a return statement or a call to the exit() function. (The only exception is when the last statement will never finish, such as an infinite for loop with no break statement. In that case, your compiler will probably complain about adding another statement that can never be reached.)
Cross Reference:
VIII.9: Is using exit() the same as using return?
No comments:
Post a Comment