Should I return 0 or 1 for successful function? [duplicate]

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?


Solution 1:

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 and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.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.

Solution 2:

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())
{
  ...
}