scanf %u

V

viza

unsigned int number;
scan=sscanf(" -76","%u",&number);
printf("number has the value %d as %%d and %u as %%u.\n",number,number);

under gcc/3.2.2* this is returning 1, and assigning a value to number.
Isn't this wrong?

My reading of the man pages is that a '-' is not allowed. Doesn't this mean
it should be impossible to make the conversion, scanf should return 0 and
number should be left alone - just like if another non allowed character
were there, (eg: a letter)?

What have I missed?

* gcc (GCC) 3.2.2 (Mandrake Linux 9.1 3.2.2-3mdk)
 
M

Mathew Hendry

unsigned int number;
scan=sscanf(" -76","%u",&number);

under gcc/3.2.2* this is returning 1, and assigning a value to number.
Isn't this wrong?

Nope, the C99 standard has this to say about the %u specifier (7.19.6.2 #12)

| u Matches an optionally signed decimal integer, whose format is the same as
| expected for the subject sequence of the strtoul function with the value 10
| for the base argument. The corresponding argument shall be a pointer to
| unsigned integer.

Notice "optionally signed". Then we need to look at the definition of
strtoul (7.20.1.4 #5) to see how it treats negative numbers

| If the subject sequence begins with a minus sign, the value resulting from
| the conversion is negated (in the return type).

strtoul's return type is unsigned long, so in this case -(unsigned long)76
would be returned.

There appears to be a weakness in the specification at this point though, as
it is not specified *scanf converts that unsigned long value to unsigned
int. The natural way would be "as if by assignment", giving
(unsigned int)-(unsigned long)76, but this is not specified anywhere AFAICT.
printf("number has the value %d as %%d and %u as %%u.\n",number,number);

This line has undefined behaviour, because the first conversion specifier
(%d) does not match the type of ''number''.

-- Mat.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top