0

Can someone explain why unsigned int is taking a negative value? An unsigned int should take only positive values.

From Wikipedia:

word, long, doubleword, longword, int

Unsigned: From 0 to 4,294,967,295 which equals 2^32 − 1

#include <stdio.h>
typedef unsigned int uint32;

int main()
{
     uint32 i;
     int x = -1;
     i = x%32;
     printf("\n\n Value of uint32 i = %d", i);
     return (0);
}

Output:

Value of uint32 i = -1

Below is the explanation which I found in cpp standard, which I am unable to interpret.

For each of the signed integer types, there exists a corresponding (but different) unsigned integer type: “unsigned char”, “unsigned short int”, “unsigned int”, and “unsigned long int,” each of which occupies the same amount of storage and has the same alignment requirements (3.9) as the corresponding signed integer type40) ; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same.

4 Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer

40) See 7.1.5.2 regarding the correspondence between types and the sequences of type-specifiers that designate them.

41) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

entryton
  • 280
  • 5
  • 18
user617554
  • 49
  • 2
  • 6

2 Answers2

18

You are using the wrong flag for printf. It should be %u.

printf("\n\n Value of uint32 i = %u", i);

RedX
  • 14,749
  • 1
  • 53
  • 76
7

The same bit pattern can be interpreted in many different ways. The only difference between a signed and an unsigned integer is in the way their bit patterns are interpreted. Your code instructs printf to interpret an unsigned int as signed, that's why you see a negative number.

As a matter of experimenting, try this:

printf("%u\n", -1);

This will produce a large positive number - a situation directly opposite of what you described in your post. Again, printf is asked to interpret a signed number as an unsigned, so it happily throws the sign away, and prints the value as if it were unsigned.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523