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.