C or C++ Return Status

Jason Marcell picture Jason Marcell · Sep 16, 2011 · Viewed 14.6k times · Source

What are the best practices for writing C or C++ functions that return an int that represents a status code?

Specifically, I want to know about the client usage but other tips are welcome.

For example, can I write something like this:

int foo() {
  return 0;  // because everything was cool
}

And then use it like this?

if (foo()) {
  // what to do if false, e.g. non-zero, e.g. not OK
} else {
  // what to do if true, e.g. zero, e.g. OK
}

This should work because best practices typically dictate that a status code of 0 means everything was OK and also 0 means false in a boolean statement.

However, this wouldn't be good, right:

if (!foo()) {
  // what to do if true
} else {
  // what to do if false
}

Answer

Oscar Korz picture Oscar Korz · Sep 16, 2011

We use this in C where I work:

int err = foo();
if (err) {
    // armageddon
}

The assignment and if could be combined, but with more complicated function calls it gets more confusing and some people are confused by assignment in a conditional (and gcc hates it).

For C++, I would prefer exceptions if available, otherwise the above.

Edit: I would recommend returning 0 on success and anything else on error. This is what unix command line utilities do.