Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning error codes from a C function which returns object pointer?

Tags:

c

This is the signature of my object create function:

struct object *object_create();

If the object is successfully created it it returns pointer to the object, and 0 otherwise.

How would I return some error codes from the same function? I need about ten codes.

I suppose mixing error codes and object pointer is not the way to go?

like image 844
Danijel Avatar asked Sep 02 '25 06:09

Danijel


1 Answers

There are pretty much only two acceptable options:

  1. struct object *object_create (myerr_t* result, /* ... */);
    Return the struct and pass the function result as parameter.

  2. myerr_t object_create (struct object** obj, /* ... */);
    Return the function result and pass a pointer to the struct by parameter.

Pros of 1:

  • It has the advantage that you can assign variables directly on the caller side:
    struct object* obj = object_create(/* ... */);
  • Pointer-to-pointer interfaces add a slight bit of complexity which can be avoided this way.

Pros of 2:

  • Reserving the return value of a function for an error code is an industry "de facto" standard way of designing APIs/libs. It is common to to use the same result type for the whole lib and have every function return it.
  • You have the option not to modify the struct in case of errors, leaving the caller's variable intact. Mainly matters in case of "realloc-like" interfaces.

I would not advise anyone to use errno because using a global error result variable is obscure, error prone, severely restricted and (pre-C11) not thread-safe. Also it might conflict with skunky, legacy error handling by various standard/POSIX lib functions.

I would not advise to use any wrapper hacks either, such as wrapping the returned struct in a larger one or over-allocating an error code at the end. This just adds complexity and potential for bugs.

An error handler should be simple, not introduce potential errors of its own due to added complexity! Anything else but a plain enum result code is questionable practice.

like image 142
Lundin Avatar answered Sep 04 '25 18:09

Lundin