Possible Duplicate:
Error handling in C code
What return value should you use for a failed function call in C?
I always use 0, but its not really readable in if
, while
, etc.
Should I return 1? Why main function return 0
for success?
return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false.
Having a single exit point from a program makes a good place to put a breakpoint. Having a single execution flow makes it easier to follow a program if you're unfamiliar with it. As to the other two, you can't use return 0; if you also want to have a single exit point as well as indicate abnormal termination.
No, its not necessary. Here int is the return type of the main program. The main function returns nothing generally, thus we are writing 'return 0' at the end of it.
The main function in a C program returns 0 because the main() method is defined and imported first when the code is run in memory. The very first commands within the main() function are implemented. Until all commands of code have been accomplished, the program must be removed from memory.
It's defined by the C standard as 0
for success (credits go to hvd).
But
For greater portability, you can use the macros
EXIT_SUCCESS
andEXIT_FAILURE
for the conventional status value for success and failure, respectively. They are declared in the filestdlib.h
.
(I'm talking about the value returned to the OS from main, exit or similar calls)
As for your function, return what you wish and makes code more readable, as long as you keep it that way along your programs.
The reason why main
use 0
for success is that it is used as the exit code of the application to the operating system, where 0
typically means success and 1
(or higher) means failure. (Of course, you should always use the predefined macros EXIT_SUCCESS
and EXIT_FAILURE
.)
Inside an application, however, it's more natural to use zero for failure and non-zero for success, as the return value can directly be used in an if
as in:
if (my_func()) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With