Sujet : Re: The difference between strtol() and strtoul() ?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 20. Jun 2024, 22:37:29
Autres entêtes
Organisation : None to speak of
Message-ID : <87r0crwb1i.fsf@nosuchdomain.example.com>
References : 1 2
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
scott@slp53.sl.home (Scott Lurndal) writes:
[snip]
The strtoul/strtoull function semantics match the C language semantics.
>
$ cat /tmp/a.c
#include <stdio.h>
int main(int argc, const char **argv)
{
unsigned long v = -1ul;
>
printf("0x%lx\n", v);
return 0;
}
$ cc -Wall -Werror -o /tmp/a /tmp/a.c
$ /tmp/a
0xffffffffffffffff
$
The functions accept a syntax that doesn't exactly match anything
in C's grammar.
Both accept integer constants and a restricted subset of other
integer constant expressions. "1", "+1", and "-1" are accepted.
"1+1" is not (nor is "- 1").
For signed integers, that's perfectly reasonable; +1 and -1 are
expressions, not constants, but users are not likely to care about
the distinction. These functions deal with user input, not C syntax.
For unsigned integers, it would have made sense to disallow signs,
or at least disallow leading '-'. The behavior of unary "-" for
unsigned integers is well defined, but probably not something that
users should need to be aware of when providing program input.
My guess is that the authors of strtol and strtoul thought
consistency between the two functions was important, and I'm not
sure I disagree -- but interpreting "-1" as 18446744073709551615
can certainly be counterintuitive.
The ANSI C Rationale indicates that the strto*() functions were
adopted from UNIX System V.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */