Why 'return 0'?
Hi: Language C: 0 is false, !=0 is true. In fact true is 0xffff...f, any number of efs, because it is all ones in binary. OK. For a regular function I return with 'return 0'. So, if f is a funcion, a= f is a= false. Why?
|
It's an exit code!
|
Usually the high bit is reserved for the sign (signed data types being more usual).
OK |
It makes perfect sense if you regard the exit code as an ENCOUNTERED_AN_ERROR flag. (As a bonus, the return value indicates which error was encountered).
|
It's clear. As in
Code:
if(some_function()) |
Quote:
Quote:
|
Of course. Thank you for you useful posts. psionl0.
"some_function is always called in this code. Only the statements in the curly braces are conditionally executed". No doubt about it. |
Quote:
Quote:
|
Quote:
eg: Code:
y = ((x == 5) * some_other_computation(x)); Code:
if (x == 5) Quote:
|
Quote:
Quote:
Quote:
|
To summarize: always read the documentation of the actual function.
Examples: malloc, fopen: NULL=error open: -1=error read: -1=error,0=eof isatty: 1=yes,0=no inet_aton: 0=error |
Quote:
|
There's also the conceptual approach; there's a variable number of ways a fn can fail (& why not supply a different value for each one), but you only need one value for success ... :)
|
Quote:
In the absence of returning a structure that includes an error code, a single return value has to include some way of indicating error codes as well as success codes. So, what H_TeXMeX_H said ... |
If a C/C++ function states to use boolean return codes, then 0 will be false. I always test against 0 (false) and treat anything else as true, no matter if stdbool.h, C++, GTK or whatever, doesn't matter if true is defined as 1 (the common standard for C/C++) or even -1. Just treat 0 as false and you're good. Still, check if the API you're using is defining an own boolean type and then use that type.
Other functions return a different return value type (other than bool, e.g., int), sometimes using a return code of zero for success and a range of other codes for multiple different outcomes, so they can pass additional information in the returncode. A software that exits (e.g., back to the shell it was launched from) either returns EXIT_SUCCESS (0) or some kind of error/failure returncode. Not boolean either. |
All times are GMT -5. The time now is 07:55 PM. |