It's quite astonishing how the historical inability of commonly used programming languages (from FORTRAN all the way to, say, Java/C#) to ergonomically return two values from a function call has caused people to invent all kinds of insane APIs/contracts.
[double x, errno_t errno] = strtod(s, nullptr);
if (errno != 0) {
// ...
}
[x, _] = strtod(s, nullptr); // When you're certain the error is impossible or just don't care
Instead, we're stuck with "check if the return value is -1 and if it is, check the global variable errno" at best, and with "the function doesn't really reliably reports its errors so don't feed it malformed data, idc" at worst.
gucci-on-fleek 8 hours ago [-]
C has supported struct returns since at least C89:
> Needing to typedef a unique struct for every possible function return type isn't very ergonomic, but you can work around that with C23:
I think you’ve unraveled the mystery of why that didn’t catch on in nearly 40 years of C.
Honestly it’s got to be the biggest disappointment in computer science that nothing has displaced C as the Franca Lingua. And now with the advent of AI, I don’t think anyone is going to care anymore. Rust will be the future, but not because it’s ergonomic, but because it can prevent memory errors.
wongarsu 7 hours ago [-]
Java and C# famously solve this with a hidden implicit return value for errors: the exception. The current trend in language design is to take the same idea and make it explicit instead, using sum types. Like Rust's `Result`, where the result contains either the normal value or an error, but never both
Of course C++ gives you the option to do any of the above, and still contains insane API contracts
TeMPOraL 4 hours ago [-]
That doesn't solve the whole problem, though - as per the rule, "zero, one, infinity", you often want to return more than two values, and often none of them represents an error.
qznc 7 hours ago [-]
I would not describe exceptions as return values. Speaking in a C context, exceptions are more like "longjmp" than "return".
Arguably the better solution compared to these "algebraic sum types" (they go by countless different names) are set-theoretic union types, used by a few languages such as TypeScript.
They allow for types like "String or Integer". A function which returns a value of type "A" can automatically also be assigned to a variable of type "A or B", and a function which accepts a parameter of type "A or B" can automatically also be passed a variable of type "A". This is not the case for algebraic sum types, which require somewhat inconvenient wrapping or unwrapping.
Unlike algebraic sum types, set-theoretic union types are also not necessarily mutually exclusive. E.g. a number of type "Integer or Float" could be both. Moreover, set-theoretic types can be generalized to arbitrary Boolean combinations of types, e.g. "A or (B and not C)", possibly involving disjunctions, conjunctions, and negations (since {and, or, not} are functionally complete). That's not possible for algebraic sum/product data types. Though there is no mainstream language yet with a set-theoretic type system that supports negation types.
tialaramex 5 hours ago [-]
This choice has nice ergonomics but brutal practical cost so that's why languages close to the metal do not want to do this and particularly don't want to go around defaulting to it whereas a language like Typescript is fine with it.
cubefox 3 hours ago [-]
Maybe it has "brutal practical cost", I don't know, but even most high-level languages don't have set-theoretic type systems. Perhaps because the approach is relatively new and most popular languages are old.
kaashif 9 hours ago [-]
C++/C#/Python absolutely do have ergonomic ways to do this (and have for decades by this point...) but programmers continue to use sentinel values. It is a bit puzzling.
Kevin_Flynn 4 hours ago [-]
Is returning 2 values from a function ever required ?
If your code is organized well, and your functions act on context structures, a pass/fail result, or an error code where 0 = success, and everything else is an error, or a pointer to a structure with multiple values, seems to be entirely sufficient.
I quite prefer C, over C++ and other perhaps "more expressive" languages, exactly because it is simpler. It does more with less.
"It can scarcely be denied that the supreme goal of all theory is to make the irreducible basic elements as simple and as few as possible without having to surrender the adequate representation of a single datum of experience." - Albert Einstein
lpribis 14 minutes ago [-]
> returning 2 values
> act on context structures
Same semantics but mutating context is much harder to track, so yes it is preferred to return 2 values.
tester756 7 hours ago [-]
Wut? C# besides all other ways to return Tuples, Result<T>s, NULLable, etc, etc.
Still had something as sane as:
if (double.TryParse("5.x5", out var val))
{
Console.WriteLine(val);
}
else
{
Console.WriteLine("err");
}
sdcfgy 7 hours ago [-]
When I write C I tend to always return any error code on the stack and pass the pointer to where I want the result to go. Makes managing memory easier. The owner gets to allocate.
Example:
#define E_DIVZERO -100
int divide(float a, float b, float *result) {
if (b == 0.0) return E_DIVZERO;
*result = a / b;
}
quietbritishjim 5 hours ago [-]
I agree, but you're missing the `return E_SUCCESS` at the end :-)
sdcfgy 4 hours ago [-]
Good catch. That was pre-coffee :)
muvlon 8 hours ago [-]
Heck, even using multiple returns for this feels like a kludge to me at this point, when more advanced languages like TypeScript, Rust or Zig offer sum types/tagged unions.
cubefox 5 hours ago [-]
Strictly speaking the unions in TS are untagged/set-theoretic, which is different from Rust or Zig.
win311fwg 4 hours ago [-]
Except often you want disjoined return arguments, while sum types setup an either-or situation. You can resort to tuples/arrays, but then that questions why the languages support multiple input arguments when tuples can be equally used for input. Frankly, any language that accepts multiple input arguments but only allows one return argument didn't have much thought put into it.
StilesCrisis 4 hours ago [-]
C allows struct returns, and C++ allows something quite close to what you've written verbatim. But in 1989, there was less of a focus on error handling; most code wasn't checking errno at all, so why spend time returning it to every caller?
dwattttt 8 hours ago [-]
I'd argue it's as much a mentality as language barrier; high assurance code would typically always return an error code, and use out parameters rather than return values. This has been possible for as long as C has existed (I imagine), it's just not common practice.
I have a pet theory that new languages benefit at least as much from an opportunity to reset "common practice" / defaults as they do syntax/semantic improvements.
edwcross 8 hours ago [-]
errno is global, but also _Thread_local, to help mitigate issues in a multithreaded environment. A kludge over a kludge...
jdthedisciple 7 hours ago [-]
Tbf from what I coarsely remember having > 1 return value from a function was taught as bad practice and to be avoided in my days...
psychoslave 7 hours ago [-]
Doesn't even need two return values. One tagged union suffices:
Result(double) x = strtod·or·error(s);
if (!x.ok) {
handle(x.error);
return;
}
use(x.value);
Which in real C, with no language support, is just:
typedef struct {
double value;
int error; /* 0 = ok */
} maybe·double;
maybe·double x = strtod·or·error(s, NULL);
if (x.error) { /* handle */ }
win311fwg 4 hours ago [-]
Why no tagged unions in the C version?
typedef struct {
_Bool ok;
union {
double value;
int error;
};
} Result_double;
Result_double x = strtod·or·error(s, NULL);
if (!x.ok) {
handle(x.error);
return;
}
use(x.value);
fragmede 9 hours ago [-]
Thank you for reminding me that, while Python is slow, there are still reasons to pick it over the alternatives.
nvme0n1p1 9 hours ago [-]
Basically all commonly used languages support this nowadays. Even ones you might not expect like C++ and C# have added it. The only major exceptions that come to mind are C and Java.
RossBencina 8 hours ago [-]
You have been able to return a struct by value in C since at least C89:
typedef struct {
double d;
int err;
} Ret;
Ret foo(void) {
Ret r = { 0.0, 43};
return r;
}
int main() {
Ret r = foo();
}
You can't return a bare fixed-size array though.
Panzerschrek 10 hours ago [-]
C number parsing functions are fundamentally broken, since they are locale-dependend. There are many bugs when one parses a number assuming it has decimal point, but later on systems with locale different from one used on developer's machine it may be suddenly comma instead of point. So, one should avoid using them almost always and use std::from_chars (available in new C++ versions) or some other thirdparty library.
spacechild1 9 hours ago [-]
+1 for `std::from_chars`. It's also by far the fastest of all standard conversion routines.
raverbashing 9 hours ago [-]
And errno
errno is a worse mistake than null pointers in general
gucci-on-fleek 8 hours ago [-]
> the linux man pages for these functions literally don't mention this at all
> the fact that the man page never makes any note of this being an extension ([…]) is really notable to me.
> this is completely undocumented on the linux man page.
The Linux man page maintainers are really friendly in my experience, so it's probably worth reporting this to them [0] [1].
For good reasons. The VAX floating point specification was much worse, even if somewhat cheaper to implement.
IEEE 754 was one of the few standards that caused a significant progress of the standardized domain, because what is important for users had precedence over what is important for vendors.
Before IEEE 754, all floating-point implementations attempted to minimize the hardware cost, regardless of what aberrant behavior this would cause, which would confuse the naive users.
RossBencina 7 hours ago [-]
For a long time Microsoft's strtod implementation was broken, I'd think most people would be using netlib or one of the newer algorithms.
> No portable way to detect string-to-float conversion errors in standard C
There isn't just 1 standard C, theres many. AI says theres 5.
There are 5 major ISO C standards: C90, C99, C11, C17/C18, and C23. C89 is essentially the same standard as C90 under its ANSI name, and C95 was an amendment rather than a separate major edition. The latest is C23.
POSIX, as you know, stands for "Portable Operating System Interface."
> posix doesn't give a shit about math_errhandling; it always requires the implementation to set errno if overflow or underflow occurs.
So, POSIX, the "Portable" interface, specifies that underflow/overflow errors are always reported.
The problem seems to be in the headline, not the spec.
j16sdiz 11 hours ago [-]
yes. that's why many number crunching app ships / vendors their own math library
anitil 11 hours ago [-]
Even putting aside the ugliness of errno, this is pretty bad. I'm at the point with libc where I try to use as little of it as I can, though I'm not writing a lot of C these days
signa11 10 hours ago [-]
well, unless you are 'syscalling' someone else is doing it on your behalf.
eptcyka 9 hours ago [-]
More to libc than syscalls.
PhilipRoman 8 hours ago [-]
I would say there are 3 broad classes of libc functions
1) functions that you cannot implement in portable C - syscalls, signals, ABI specific things like longjmp and setcontext
2) functions that you could implement by yourself in portable C, but they are expected to play nice with the rest of the system - a lot of POSIX user stuff, dns management, dlopen, all the nsswitch mess. Can't think of any standard C examples because of the extreme portability requirements of C. Maybe the locale stuff, although it's usefulness is dubious.
3) functions that are there for convenience and sometimes compiler special-casing, like math, str*, <db.h> stuff that was thankfully removed from glibc
Most of #3 should be ignored. #2 is optional, especially if your software is for end users and not packaged by a distro. Sometimes it's safer to ship your own MDNS implementation for example rather than hope that the distro has sane defaults.
eptcyka 8 hours ago [-]
I'd much rather push for a world where we use a reasonable DNS/mDNS implementation on Linux rather than add to the zoo of bespoke variants. I have written code that tries to appease different DNS managers across different versions of them for different distros. We need to stop. Everyone believes that the common way of handling DNS is insane, so they create their own new way of doing it.
ofcourse. forgot the tongue-firmly-in-the-cheek disclaimer.
oso2k 8 hours ago [-]
Sometimes I wish we could get to a timeline where the FPU format standards have something like Crockford’s DEC64 end up winning or evolving into the prevailing standard. Simpler & consistent math ought not to be this hard.
Just don't make the errors, then you don't have to detect them.
When your app stops issuing these errors, then you won't have to write blog posts complaining that someone elses code can't handle your errors.
Definitely you should never be converting strings to floats ever anyways, see how I'm going on a limb here without any knowledge of your application, but then you know that I'm right because there's no reason why you would ever do that?
CamperBob2 11 hours ago [-]
if (sscanf(string,"%lf",&foo) != 1)
{
bad_float();
}
This has the benefit of handling scientific notation, too, which some of the other CRTL functions inexplicably do not.
For extra reassurance, initialize foo to NaN or DBL_MAX or something, and verify that it is no longer equal to that value.
lelanthran 10 hours ago [-]
That doesn't detect overflows and underflows. Also changes based on locale, which is not thread safe (so you cannot set locale, convert, then unset locale).
That's a feature: Where did the string come from if not the user?
> you cannot set locale, convert, then unset locale
So what? You're not handling multiple locales: You're using the user's locale. If you're making a server, using anything but LANG=C or a utf8 variant is asking for trouble.
I think the point is it's absolutely possible to portably detect errors, some libc's strtod() just don't which ain't the same thing.
daemin 7 hours ago [-]
>> Also changes based on locale,
> That's a feature: Where did the string come from if not the user?
Many games and applications store floating point values in text file formats. This has caused bugs in those programs many times over because they didn't realise it was locale dependent and the data parsing broke in another locale.
geocar 5 hours ago [-]
> Many games and applications store floating point values in text file formats.
And why, pray tell, would those games and applications ship with text files containing floating point values that were invalid?
Certainly if they produce the values, strtod() is sure to work, and worrying about errors at that level just doesn't make any sense at all.
> This has caused bugs in those programs
I'm sorry this just isn't true: The programmer caused the bugs in those programs and nobody else.
Meanwhile users who produce text files with floating point numbers in their locale expect program that load those text files to tolerate their locale, and those programs should not be using strtod()!
rwmj 5 hours ago [-]
Annoyingly this doesn't detect certain errors. This is one thing I'd like to change in the next C standard, but (from discussions I had with someone who works in those standards) they don't want to break existing code. Which seems like a very bogus justification to me as that code is broken already.
Also the locale thing could be solved by adding another %-directive to say "this format string should be treated in the C locale", like %C (if it's not already used).
IOW this could be made to work, but human factors prevent it.
shakna 10 hours ago [-]
sscanf has locale things that make it include implementation-defined behaviour, doesn't it?
tliltocatl 9 hours ago [-]
Anything that isn't C.UTF-8 is totally broken anyway.
PhilipRoman 8 hours ago [-]
Case in point: echo y | LANG=lv_LV.UTF-8 grep '[a-z]'
Rendered at 15:25:53 GMT+0000 (UTC) with Wasmer Edge.
I think you’ve unraveled the mystery of why that didn’t catch on in nearly 40 years of C.
Honestly it’s got to be the biggest disappointment in computer science that nothing has displaced C as the Franca Lingua. And now with the advent of AI, I don’t think anyone is going to care anymore. Rust will be the future, but not because it’s ergonomic, but because it can prevent memory errors.
Of course C++ gives you the option to do any of the above, and still contains insane API contracts
They allow for types like "String or Integer". A function which returns a value of type "A" can automatically also be assigned to a variable of type "A or B", and a function which accepts a parameter of type "A or B" can automatically also be passed a variable of type "A". This is not the case for algebraic sum types, which require somewhat inconvenient wrapping or unwrapping.
Unlike algebraic sum types, set-theoretic union types are also not necessarily mutually exclusive. E.g. a number of type "Integer or Float" could be both. Moreover, set-theoretic types can be generalized to arbitrary Boolean combinations of types, e.g. "A or (B and not C)", possibly involving disjunctions, conjunctions, and negations (since {and, or, not} are functionally complete). That's not possible for algebraic sum/product data types. Though there is no mainstream language yet with a set-theoretic type system that supports negation types.
If your code is organized well, and your functions act on context structures, a pass/fail result, or an error code where 0 = success, and everything else is an error, or a pointer to a structure with multiple values, seems to be entirely sufficient.
I quite prefer C, over C++ and other perhaps "more expressive" languages, exactly because it is simpler. It does more with less.
"It can scarcely be denied that the supreme goal of all theory is to make the irreducible basic elements as simple and as few as possible without having to surrender the adequate representation of a single datum of experience." - Albert Einstein
> act on context structures
Same semantics but mutating context is much harder to track, so yes it is preferred to return 2 values.
Still had something as sane as:
if (double.TryParse("5.x5", out var val)) { Console.WriteLine(val); } else { Console.WriteLine("err"); }
Example:
I have a pet theory that new languages benefit at least as much from an opportunity to reset "common practice" / defaults as they do syntax/semantic improvements.
errno is a worse mistake than null pointers in general
> the fact that the man page never makes any note of this being an extension ([…]) is really notable to me.
> this is completely undocumented on the linux man page.
The Linux man page maintainers are really friendly in my experience, so it's probably worth reporting this to them [0] [1].
[0]: https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/...
[1]: https://lore.kernel.org/linux-man/
https://en.wikipedia.org/wiki/IEEE_754
https://sixlettervariable.blogspot.com/2007/05/vax-floating-...
IEEE 754 was one of the few standards that caused a significant progress of the standardized domain, because what is important for users had precedence over what is important for vendors.
Before IEEE 754, all floating-point implementations attempted to minimize the hardware cost, regardless of what aberrant behavior this would cause, which would confuse the naive users.
https://www.exploringbinary.com/visual-c-plus-plus-strtod-st...
https://lemire.me/blog/2026/02/01/converting-floats-to-strin...
There isn't just 1 standard C, theres many. AI says theres 5.
There are 5 major ISO C standards: C90, C99, C11, C17/C18, and C23. C89 is essentially the same standard as C90 under its ANSI name, and C95 was an amendment rather than a separate major edition. The latest is C23.
POSIX, as you know, stands for "Portable Operating System Interface."
> posix doesn't give a shit about math_errhandling; it always requires the implementation to set errno if overflow or underflow occurs.
So, POSIX, the "Portable" interface, specifies that underflow/overflow errors are always reported.
The problem seems to be in the headline, not the spec.
1) functions that you cannot implement in portable C - syscalls, signals, ABI specific things like longjmp and setcontext
2) functions that you could implement by yourself in portable C, but they are expected to play nice with the rest of the system - a lot of POSIX user stuff, dns management, dlopen, all the nsswitch mess. Can't think of any standard C examples because of the extreme portability requirements of C. Maybe the locale stuff, although it's usefulness is dubious.
3) functions that are there for convenience and sometimes compiler special-casing, like math, str*, <db.h> stuff that was thankfully removed from glibc
Most of #3 should be ignored. #2 is optional, especially if your software is for end users and not packaged by a distro. Sometimes it's safer to ship your own MDNS implementation for example rather than hope that the distro has sane defaults.
https://www.crockford.com/dec64.html
Gilfoyle: Anything to do with errors is more your vibe"
https://www.youtube.com/watch?v=oyVksFviJVE&t=49
Oh, this one is easy.
Just don't make the errors, then you don't have to detect them.
When your app stops issuing these errors, then you won't have to write blog posts complaining that someone elses code can't handle your errors.
Definitely you should never be converting strings to floats ever anyways, see how I'm going on a limb here without any knowledge of your application, but then you know that I'm right because there's no reason why you would ever do that?
For extra reassurance, initialize foo to NaN or DBL_MAX or something, and verify that it is no longer equal to that value.
A trivial change does though: Just round-trip it.
> Also changes based on locale,That's a feature: Where did the string come from if not the user?
> you cannot set locale, convert, then unset locale
So what? You're not handling multiple locales: You're using the user's locale. If you're making a server, using anything but LANG=C or a utf8 variant is asking for trouble.
I think the point is it's absolutely possible to portably detect errors, some libc's strtod() just don't which ain't the same thing.
> That's a feature: Where did the string come from if not the user?
Many games and applications store floating point values in text file formats. This has caused bugs in those programs many times over because they didn't realise it was locale dependent and the data parsing broke in another locale.
And why, pray tell, would those games and applications ship with text files containing floating point values that were invalid?
Certainly if they produce the values, strtod() is sure to work, and worrying about errors at that level just doesn't make any sense at all.
> This has caused bugs in those programs
I'm sorry this just isn't true: The programmer caused the bugs in those programs and nobody else.
Meanwhile users who produce text files with floating point numbers in their locale expect program that load those text files to tolerate their locale, and those programs should not be using strtod()!
Also the locale thing could be solved by adding another %-directive to say "this format string should be treated in the C locale", like %C (if it's not already used).
IOW this could be made to work, but human factors prevent it.