Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c++ - How do unsigned integers work

As the title suggests, I am curious about how an unsigned int (or things like NSUInteger, u_int_blah, but I assume these are all typedefs of the same thing) works. For example, when their value drops below zero, is an exeption raised? Will an error occur? One specific example of this would be indirectly setting the value to a negative number.

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


Also, another way to indirectly set it would be to have the user input it.

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


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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When a unsigned comparing with signed, they will all be cast into unsigned. The procedure is relative to how the data is stored in memory. In binary, a minus number( like -3), will be stored like :

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

you can tell that -3 can be like :

// 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 

So the loop:

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

will be like

// 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...