How unsigned integers work

As the title suggests, I wonder how it works unsigned int(or things like NSUInteger, u_int_blahbut I guess it's all typedefthe same thing). For example, when their value falls below zero, does an increase occur? Has an error occurred? One specific example of this will indirectly set a value to a negative number.

for (unsigned int x = 5; x > -10; x--) {
    // will x ever reach below zero, or will the loop terminate
}


In addition, another way to indirectly establish this would be for the user to enter it.

printf("Enter a number");
unsigned int x;
scanf("%ud", &x); // user enters something like -29


So, I have three questions. That stops and unsigned int from assigning to a negative number ( unsigned int x = - 3). How this behavior is implemented (by the compiler or in other ways). What happens when an unsigned int is assigned (directly or indirectly) to a negative value. Is the data corrupted? Is this an overflow?
Thankyou

+4
source share
3 answers

When you assign a negative number

unsigned int = -1;

The number you received will be 4294967295, or 4 ^ 8 -1

because the size of the integer is 4 bytes, or 4 ^ 8 = 4294967296

An integer will wrap around this number if it is negative

+2
source

, unsigned. , . (, -3) :

-3 : 1111 1111 1111 1101
3  : 0000 0000 0000 0011

, -3 :

// result  : 0000 0000 0000 0011

result = for_every_bit_of_3( not **ThisBit** );  
// result  : 1111 1111 1111 1100 

result = result + 1;
// result  : 1111 1111 1111 1101 

, :

for (unsigned int x = 5; x > -10; x--) {
    // will x ever reach below zero, or will the loop terminate
}

// 4,294,967,286 is what -10 cast to unsigned
for (unsigned int x = 5; x > 4294967286; x--) {
    // will x ever reach below zero, or will the loop terminate
}
+3

( , gcc -Wno-sign-compare). , , (http://en.wikipedia.org/wiki/Two%27s_complement), , -10 , 4294967286 ( 4 , 2 * INT_MAX - 10), 5. , , , , .

+1

Source: https://habr.com/ru/post/1534572/


All Articles