Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf %u negative number?

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 ?

like image 775
rondino Avatar asked Jul 31 '16 13:07

rondino


People also ask

Does Strtol work with negative numbers?

If the value is negative, the strtol() function will return LONG_MIN, and the strtoll() function will return LONGLONG_MIN. If no characters are converted, the strtoll() and strtol() functions will set errno to EINVAL and 0 is returned.

Can we convert negative int to char?

Yes. Negative numbers can be assigned to char variables.

Which function is used to read data from the console in C?

In C, the scanf() function is used to read formatted data from the console.


1 Answers

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

like image 137
Sourav Ghosh Avatar answered Oct 18 '22 17:10

Sourav Ghosh