scanf("%u") accepts negative ints
Qijian Zhang
qijian.zhang@qq.com
Thu Aug 2 02:32:00 GMT 2018
`u` matches an unsigned decimal integer.
The format of the number is the same as expected by `strtoul()` with the value 10 for the base argument.
`strtoul()`:
Discards any whitespace characters (as identified by calling `isspace()`) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following part:
* (optional) plus or minus sign
* (optional) prefix (0) indicating octal base (applies only when the base is 8 or 0)
* (optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or 0)
* a sequence of digits
If the *minus sign* was part of the input sequence, the numeric value calculated from the sequence of digits is *negated* as if by unary minus in the result type, which applies *unsigned integer wraparound rules*.
Check this docs: https://devdocs.io/c/io/fscanf#Parameters (https://link.getmailspring.com/link/1533176303.local-f1e8e841-d41d-v1.3.0-fd741eb7@getmailspring.com/0?redirect=https%3A%2F%2Fdevdocs.io%2Fc%2Fio%2Ffscanf%23Parameters&recipient=bGliYy1oZWxwQHNvdXJjZXdhcmUub3Jn)
On 8月 2 2018, at 6:42 早上, Martin Castillo <castilma@uni-bremen.de> wrote:
>
> Hi,
> I just discovered that the scanf() family does parse negative ints and
> casts them to the unsigned type, where %u has been specified.
> The documentation says "u Matches an unsigned decimal integer;",
> so I am surprised that it does not returns with a matching error.
>
> Can someone explain me this behaviour?
> Thanks,
> Martin Castillo
>
> scan.c:
> #include <stdio.h>
> int main() {
> unsigned int u=5;
> int ret = sscanf("-1","%u",&u);
> if (ret == 1) {
> printf("%u\n",u);
> }
> }
>
More information about the Libc-help
mailing list