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 ?
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.
Yes. Negative numbers can be assigned to char variables.
In C, the scanf() function is used to read formatted data from the console.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With