if ret val 0 is ok then -1 is error
else
if ret val 0 is error then 1 is ok

Started: 19Oct2016. Last updated 25Oct2016
This page is in group Technology and is about a point or two one could be aware of when using third-party code. Some do it this way, some that way, and you perhaps your way. And I, my way? If you always test returns from function calls of third-party C code you can skip this note, as you would know it.

Limited selfrefs

See first Limited selfrefs. In short:  I am not referring to (m)any of my own blog notes directly in the text. However, with this theme there should be no notes to refer to directly.

This is going to be a small epistle on the fact that different C coders (hopefully not the same) use “return value 0” from a function both if something is in error and/or if it’s ok. C coders would correspondingly return 1 if ok or -1 if error. Some times this is confusing, so I’ll write about it.

The first corresponds to use as typical ok / not ok:

typedef enum {false,true} bool;
bool positive_ok (const int input) {
    bool positive_ok;
    if (input>=0) {positive_ok=true;} else {positive_ok=false;}
    return positive_ok; // 0 if error
}

The second refers to the situation where, in some cases a full range of error messages is needed (often through the “errno” value, see below). However, in most cases I’d say that 0 and -1 are used as ok / not ok:

#define OK (0)
#define ERROR (-1) // or a list of negative or positive error messages
// ..but the coder knows best and consequently uses values 0 and -1 instead:
int positive_OK (const int input) {
    if (input>=0) {return 0;} else {return (-1);}
}

They would probably be compiled into equal code blocks.

Finally, here’s the errno that is ok to know about:

#include <errno.h>
Wikipedia: Most functions indicate that they detected an error by returning a special value, typically NULL for functions that return pointers, and −1 for functions that return integers

That concludes this shortest of all my blog notes!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.