I’m a CS student at the Technion, I have just learned of errno variable and c-style function calls.
This makes me wonder, if c-style syscalls use registers to return a value, why should anyone use errno at all?
I’m a CS student at the Technion, I have just learned of errno variable
Share
The main reason for using
errnois to give more information about the error condition.This is especially useful in situations where most (or even all) possible return values of a function are actually valid return values.
Consider the
fopen()function, which returns a pointer to aFILE. Every possible return value is also a valid return value, exceptNULL. Sofopen()returnsNULLon failure. But then you can’t tell what exactly made the function fail. Hence,fopen()useserrnoto denote the exact error condition, i.e. the file doesn’t exist, or you don’t have permission to read it, or the system is out of memory, or whatever.You can think of
errnoas a global variable (which it used to be until threads became popular). Nowadays,errnois usually a macro wrapping a function call returning the error condition. But this is just C’s way of implementing thread-specific global variables.The alternatives to
errnoare less comfortable:You could supply a function with a pointer to an
int, and the function can store its error condition there.strtod()is a good example of this technique. But this makes the API more complicated and hence less desirable. Also, it forces the programmer to define a newint, which is annoying if you don’t care if the function fails.In languages that allow more than one return value (and don’t feature exceptions), it’s common to return two values: one for the actual result and another to denote the error condition. In languages like Go, you see code like the following:
Don’t trust people who claim that
errnois an “old” technique and hence to be avoided. The machine you’re programming is far older thanerrnoor even C, and nobody has ever complained about that.