问题
While i am running the program below it outputs like 109876543210-1-2-3-4-5-6-78-9-10-11-12-and s0 on. Why so? What is the concept of unsigned integer?
main ()
{
unsigned int i;
for (i = 10; i >= 0; i--)
printf ("%d", i);
}
回答1:
Unsigned integers are always non-negative, that is greater than or equal to 0. When you subtract 1 from 0 in an unsigned integer type you end up with MAX_INT.
Therefore, your for loop will never terminate.
However, you need to use "%u" not "%d" in your printf if you want it to print the unsigned value rather than the signed value.
回答2:
The %d
format string treats the substituted value as int
, which is signed.
回答3:
Why so?
Because your program has an undefined behavior (using %d
which is for int
to print an unsigned
) - so you can expect anything to happen.
Why the infinite loop? Because an unsigned int
is always >= 0
.
What is the concept of unsigned integer?
It's an... unsigned integer. A whole number which is non-negative.
回答4:
You use %d
, so printf interprets the value as signed.
Comparison to zero (>=0) of unsigned is always true.
So, while values are from 10 to 0, the output is ok (109876543210). After that the value becomes huge positive (maximum value, for 32bit int it is 0xFFFFFFFF
). Comparison to 0 is true, so the loop continues. But in printf
0xFFFFFFFF
produces -1
since %d
is used. Then the loop continues to 0xFFFFFFFE
which is -2
but still >= 0
as unsigned.
Use %u
.
回答5:
printf
can't know the type of the variable you give it, all it gets is the value (the bits themselves). You have to tell it how to interpret that value, and with %d
you tell it to interpret it as a signed integer.
回答6:
You are using "%d" with printf() which is the format specifier for a signed integer.
回答7:
The declaration unsigned integer
instructs the compiler to use unsigned operations on the variable. For example, the >>
operator has different behavior on unsigned integers vs signed (specifically, whether it should preserve the sign bit).
To print an unsigned integer, you should use the %u
formatting.
回答8:
Signed integers (we'll use 16 bit) range from -32768 to 32767 (0x8000 to 0x7FFF) while unsigned integers range from 0 to 65535 (0x0000 to 0xFFFF). So unsigned integers cannot have negative values, which is why your loop never terminates. However, you have told the print program to format the output as if it were signed (%d
) so that you see the numbers formatted as negative values in your output. At some level, everything in a computer is just a string of bits that needs interpretation and your code example uses two different interpretations of the same bit patterns ... your unsigned int.
回答9:
You should use %u
as a format specifier in the printf, otherwise the value is casted to int
.
来源:https://stackoverflow.com/questions/15340415/unsigned-integers-in-c