scanf %u negative number?

rondino picture rondino · Jul 31, 2016 · Viewed 7.9k times · Source

I have tried scanf("%u",&number) and I have entered negative number the problem is when I printf("%d",number) I get the negative number. I thought this will prevent me from reading negative number. Are scanf("%d",&number) and scanf("%u",&number) the same thing really ? or is it only for readibility.

Am I doing something called undefined behavior so ?

EDIT:

From Wikipedia I read this:

%u : Scan for decimal unsigned int (Note that in the C99 standard the input value minus sign is optional, so if a minus sign is read, no errors will arise and the result will be the two's complement of a negative number, likely a very large value.

It is a little bit confusing reading SO answers and above. Can someone make it more clear ?

Answer

Sourav Ghosh picture Sourav Ghosh · Jul 31, 2016

Yes, it's undefined behavior, either way.

Considering variable number is of type unsigned, %d in printf() expects an argument of signed int type, passing an unsigned type is UB.

OTOH, if number is signed type, using %u for scanning is UB in first place.

As you might have expected

[...] prevent me from reading negative number

format specifiers are not there to prevent improper input. If the format specifier does not match the supplied argument, it invokes undefined behavior.

Quoting C11, annex J.2, scenarios invoking UB,

The result of a conversion by one of the formatted input functions cannot be represented in the corresponding object, or the receiving object does not have an appropriate type