Unable to understand type unsigned int in C

I am starting to program in C and I am having a problem to understand some of the results that I get. I am inserting the code here:

#include <stdio.h> unsigned int main(void) { unsigned int x = 0; printf("%u\n",x-1); return 0; } 

The terminal is returning 4.294.967.295, and I do not understand why. I know that this value is the maximum value of a unsigned int , but in fact I was expecting some warning from the compiler that I would have to use the int type, and not the unsigned int , because the result is negative. Anyway, can anyone help me?

+4
source share
7 answers

When you use an unsigned type, all bits are used to represent non-negative values ​​(i.e.> = 0). Think about it as values ​​wrap around, so when you decrease below the lower limit (0), you wrap it to the largest value (with 32 bits, 2 ^ 32 - 1).

Also, note that you did not assign a negative value to the variable x , you simply provided an expression that subtracted 1. from it. That is.

 x-1 

vs

 x = x - 1; 

although you would receive a warning about this, it will probably depend on the compiler and the warning levels set.

+3
source

This is a fixed number of bits (32) and two additions that will take you here.

+1
source

unsigned int , because it implies that it has no sign.

Values

unsigned int represented as 32-bit values, so when you subtract one of them, it jumps from 0x00000000 to 0xFFFFFFFF, which gives you 4294967295, which you get.

+1
source

The C standard says that all unsigned arithmetic occurs in a range modulo 2 ^ N, where N is the number of bits in a type. Thus, subtracting 1 from 0 in unsigned arithmetic does not lead to -1, but in UINT_MAX.

Think of unsigned values ​​as a ring, where 0 is glued next to UINT_whatever. Regardless of whether you add, subtract, shift, multiply, even deny, you will never leave the ring. So you are allowed to do things like

  unsigned int x = -1; /* Assigns UINT_MAX. */ 
+1
source

Unsigned means that you have only positive values. Computers store numbers as binary with some rules. When you do 0 - 1, you get the maximum value int. You can read more about this: http://en.wikipedia.org/wiki/Signed_number_representations

0
source

Because unsigned int cannot store negative integers.

Please read about the addition and double complex rooms.

What happens when the top bit is set along with others, and then interpreted as a positive number.

0
source

You will not get an error because the compiler cannot know what you will do in the future.

0
source

All Articles