Sujet : Re: The difference between strtol() and strtoul() ?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 20. Jun 2024, 23:55:01
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240620154213.917@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-06-20, Kenny McCormack <
gazelle@shell.xmission.com> wrote:
Interestingly, I note that strtoul() accepts strings that begin with a sign
(+ or -). This is odd, since you'd (*) think that a sign (particularly, a
minus) would be a syntax error in parsing for an unsigned value.
unsigned int x = -42; // implementation defined result: UINT_MAX - 41
These functions seem to be geared toward the C language (perhaps writing
compilers or tooling for C). Note that these functions recognize
a leading zero for octal when base is specified as zero, and also
recognize the 0x prefix when base is 0 or 16.
So it is unsurprising that the unsigned functions would accept
negative values and do the modulo reduction.
Further, although the (Linux) man page is more than a bit murky on the
subject, it seems that the result of parsing, say, "-1", with strtoul() is
the largest unsigned value (usually, 2**N-1 or a lot of F's (in hex)).
Whereas, I would expect it to be 1 (i.e., just take the absolute value).
>
Comments? I find this all very counterintuitive.
>
(*) Or should I say, "one would" ?
>
P.S. Why isn't there a strtoi() or strtou() ? I know, of course, that
there is atoi(), but that doesn't have the error checking capability that
the strto* functions have.
I suspect, because, at the time strtol was introduced, long was the
widest integer type.
When designing an integer parsing function, why would you not just
have one function, working with the widest type?
Unfortunately, though, strtoll later had to be added.
If strtol didn't exist today, making it necessary to invent it or
something like it, that function should use the intmax_t type.
Then there wouldn't be any need to add new variants going forward.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca