return status and error handling

part of c programming

  • it is possible to use a status variable with an object that stores a status id and group id. this object can be checked for a failure status, and goto can be used to jump to an exit label at the end of the routine where all cleanup is done. gotos in c are local to the current routine. it is a bit like local exceptions
  • the status id represents an error code or general status code, the group id is a string name of the library the code belongs to. when multiple libraries are used, it would otherwise be almost impossible to synchronize error codes so that they are not ambiguous. string names are used because integer ids would again be hard to keep unambiguous
  • doing all clean-up at the end of the routine can save code deduplication. it can be useful to set variables to null values before they have been used so that the clean-up part can know, for example, what memory to free


  • this example uses a reference implementation from sph-sc-lib
  • status_declare declares a local variable status_t status = {0, ""};, the other status_* bindings use that variable
  • status_require checks that status.id is status_id_success, which is zero, and goes to exit if not
  • this is compatible with common error handling using int error codes, where 0 means no error
#include "sph/status.c"

status_t test() {
  if (1 < 2) {
    status_set_goto("mylib", 456);
  return status;

int main() {
  // code ...
  // more code ...
  return status.id;