tags:

views:

353

answers:

4

Hi All, I am new to C, What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int:

  1 /*
  2  * =====================================================================================
  3  *
  4  *       Filename:  prog4.c
  5  *
  6  * =====================================================================================
  7  */
  8 
  9 #include <stdio.h>
 10 
 11 int main(void){
 12 
 13     int v1 =0, v2=0;
 14     unsigned int sum;
 15     
 16     v1 = 10;
 17     v2 = 20;
 18     
 19     sum = v1 - v2;
 20     
 21     printf("The subtraction of %i from %i is %i \n" , v1, v2, sum);
 22     
 23     return 0;
 24 }

The output is : The subtraction of 10 from 20 is -10

+16  A: 

%i is the format specifier for a signed integer; you need to use %u to print an unsigned integer.

James McNellis
Remember, because unsigned values can only store nonnegative values, subtracting one unsigned integer from another will result in an underflow if the minuend is smaller than the subtrahend, then you're going to get an underflow. Take a look: http://www.topbits.com/integer-overflow.html
helixed
very cool article, thanks
Mohammed
+1  A: 

Because unsigned int value that is stored in sum is treated like signed decimal integer in printf %i

Andrew Florko
+7  A: 

With printf, the %i format outputs a signed int. Use %u to output an unsigned int. This is a common issue when beginning C programming. To address your question, the result of v1 - v2 is -10, but sum is an unsigned int, so the real answer is probably something like 4294967286 (232 - 10). See what you get when you use The subtraction of %i from %i is %u \n. :)

Dustin
+2  A: 

Signed int and unsigned int are the same size in memory, the only difference between them is how you intepret them. Signed values use a twos complement representation.

If you put 0xFFFFFFFF in a 4 byte memory location, and then ask what is the value in there? Well if we interpret it as a signed int, then it is -1, but if we interpret it as an unsigned int then the value is 4294967295. Either way it's the same bit pattern, the difference is what meaning you give it.

When you assigned 10 - 20 into an unsigned int, you calculated a value of -10 (C doesn't do overflow or underflow checking), that's a bit pattern of 0xFFFFFFF6, which means -10 in a signed int or 4294967286 in an unsigned int. If you then tell the compiler (by using %i) to print a signed int then it interprets that bit pattern as a signed int and prints -10, if you told the compiler (by using %u) to print an unsigned int then it interprets that bit pattern as unsigned and prints 4294967286.

progrmr
So, the way I interpret the bit pattern controls the value in the memory.Thank you.
Mohammed