Should I return 0 or 1 for successful function?

CBoolean

C Problem Overview


> 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?

C Solutions


Solution 1 - C

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 - C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionziqView Question on Stackoverflow
Solution 1 - Cm0skit0View Answer on Stackoverflow
Solution 2 - CLindydancerView Answer on Stackoverflow