Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

boolean

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?

like image 210
ziq Avatar asked Mar 03 '12 19:03

ziq


People also ask

Why do successful functions return 0?

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.

Is return 0 a good practice?

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.

Is returning 0 necessary?

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.

Why only return 0 is used in C?

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.


2 Answers

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.

like image 115
m0skit0 Avatar answered Oct 16 '22 23:10

m0skit0


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()) {   ... } 
like image 27
Lindydancer Avatar answered Oct 17 '22 00:10

Lindydancer