# [question]unsigned number with negative value?

• 12-25-2009
learn
[question]unsigned number with negative value?
Hi everyone,

I am confused about the definition of the unsigned. Could anyone please help to explain the result of running a simple test code. As below.

Code:

``` void main()  {   unsigned long num_a = 4;   unsigned long num_b = 8;   unsigned long num_c;   unsigned long num_d = 1;     num_c = num_a-num_b;   num_d -= num_c;   printf(" num_c = num_a - num_b, num_c is: %ld num_d is:%ld" , num_c, num_d);    }```
The result is: num_c = num_a - num_b, num_c is: -4 num_d is:5

I thought num_c is declared as an unsigned long but it can actually present a negative number. I guess I don't have the correct understanding of the unsigned number.

question 1. for "num_c = num_a-num_b", (num_c = 4-8), can num_c, an unsigned long integer, carry a negative value? why?

question 2. for "num_d -= num_c;" num_c has a unsigned long type, but is assigned to a negative number as the result of the arithmetic, would any potential side effect be introduced if continue to use num_c in the function?
• 12-25-2009
brewbuck
Unsigned and signed integers have the same representation. You are using %ld, which is a signed decimal format specifier. Therefore, the bit pattern of the integer is printed in signed form. Whether the variable itself is signed or not doesn't have any effect. Some compilers will warn you when you make such a mistake. Obviously, in this case, it did not.

If you intend to print an unsigned integer, you should use %lu, not %ld.
• 12-26-2009
learn
Many thanks. :-)