4 ms·
Thank you, I'm aware how errno works. C has been able to return structs for the last 30 years, so returning a pair of value+error code is no big issue even in C
by gpderetta 8y ago
Thank you, I'm aware how errno works. C has been able to return structs for the last 30 years, so returning a pair of value+error code is no big issue even in C.
Optimizing errno is so easy that many compilers by default do not even update errno for many math functions because it hopelessly destroy any chance of vectorizing and aggressive optimizations.
- kazinator 8y agoYour idea would seriously uglify code. If we want the function's result and the error, we have to capture the return value in an object. If we just do if (library_function(arg).result < 0) .. we have lost the errno. For the complete analysis, we must now do: struct error; error = library_function(arg); // test error.result; if bad, work with error.num Yes we have had struct returns (proper, on-stack ones) for more than 30 years, which means we could have had API's like this for 30 years. I agree that errno for math functions isn't such a great fit. It's much better suited for I/O and resource management.
- Twisol 8y agoTo be fair, the issue of ergonomics is an artifact of C only. In a language with proper sum types (or as I like to think of them, "better enums"), the pattern would look more like this: match library_function(arg) { Ok(num) => // success Err(errno) => // failure } But since C doesn't have proper sum types, we have to approximate this pattern with things like errno or returned structs.
- gpderetta 8y agoyes, the syntax is not great, but it is not really worse than errno. Especially because you can initialize the error object at declaration point and, as you pointed out, you would otherwise need to zero errno: struct error res = library_function(arg); if (res.result) { // use res.errno ... } Also remember the whole thread is about improving the syntax for this sort of stuff. C could take (another) page from C++: auto [result, errno] = library_function(arg); if (result == -1) { // use errno ... }