I have my own return type and functions defined like this:
typedef enum xx_return_t {
success = 0,
general_error = -1,
specific_error = -2,
[...]
} xx_return_type;
xx_return_type generalFunction(void) {
if(there_was_an_error)
return general_error;
}
However I'm a bit uncertain on the error type values here; what is standard/best practice for values of error returns in C/C++ - negative or positive?
Update: Thank you for your answers! I was looking for info on both C and C++, but I also realize this raises good questions on general structure and methods specific to each language (exceptions, error codes, object returns, etc).
There are several conventions to choose from:
GetLastError()
HRESULT
, containing the specific error code.errno
In general, it is more important that you use your convention consistently, than which convention you use.
Btw, some examples of how not to do this can be found in microsoft's header files:
#define S_OK ((HRESULT)0x00000000L)
#define S_FALSE ((HRESULT)0x00000001L)
Also beware of two different error values for HANDLE
's in windows: either 0 or INVALID_HANDLE_VALUE
This is really two totally different questions (C and C++ versions) disguised as one.
In C++ the answer is simple: Use return values for...returned data values and use exceptions for error/exception cases. Don't use return values for error checking in pure C++ (a C library API to C++ is a different story).
In C you don't have that option, so I would suggest using 0 for success and negative numbers for error codes. This leaves the flexibility, if desired, to use positive numbers for additional success information (for example read
calls)
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