Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General rule: negative or positive values for error code in C/C++ [closed]

Tags:

c++

c

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).

like image 682
pbeck Avatar asked Oct 04 '12 13:10

pbeck


2 Answers

There are several conventions to choose from:

  • microsoft uses 0=FALSE=error for most of its high level api's. and let the user lookup the specific error with a global function GetLastError()
  • microsoft uses 0=ok for lower level apis, like registry, audio, or telephony. these all return a type similar to HRESULT, containing the specific error code.
  • posix functions returning a status usually return -1 for error, and let the user lookup the error via a global variable errno
  • functions returning a pointer usually return NULL for error
  • c++ STL functions return 'end' for status like 'not found'. errors like 'out-of-memory' are signalled using an exception.

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

like image 164
Willem Hengeveld Avatar answered Sep 17 '22 23:09

Willem Hengeveld


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)

like image 38
Mark B Avatar answered Sep 19 '22 23:09

Mark B