The trap of assigning negative values to unsigned numbers

Source: Internet
Author: User

Has anyone tried to assign a negative number to an unsigned integer variable? Do you know what will happen? If you haven't tried it, let's explore the secrets hidden by unsigned integers.

Let's take a look at the following:Code:

Int main ()
{
Unsigned int val =-1;
Cout <Val <Endl;

Return 0;
}

Execution result:

4294967295
Press any key to continue...

 

----------------------------------------

You may not be surprised: so big! Unexpectedly, assigning a negative value to an unsigned integer variable will generate such a large number! Why? Well, let's analyze it step by step:

First, carefully observe the output result 4294967295 and find that 4294967295 = 2 ^ 32-1, oh! It seems a little regular! But why? Let's first discuss the expression of int and unsigned int, both of which are 4 bytes, 32-bit binary representation, but one int is a symbol bit, and unsigned is not. If the int type of-1 is 1000 0000 0000 0000 0000 0000 0000 0001, convert it to unsigned Int.1000
0000 0000 0000 0000 0000 0000 0001 (Red is the symbol bit), expressed as 2 ^ 31 + 1, instead of 2 ^ 32-1! What's going on? (* ^__ ^ *) Xi ......, There is a secret hidden here! That is, the binary number of the int in the real memory is not the original code of the value, but its complement code (for ease of operation, refer to digital logic)! Before forced type conversion, the int variable-1 is stored in the memory1111 1111 1111 1111 1111 1111 1111 1111, equal to 2 ^ 32-1. Soso converts to unsigned
Int Is to read the value of the block memory and assign it to the variable! In this way, Val is changed to 4294967295, which is a super big number! Therefore, you must be cautious when dealing with unsigned int values! If an error occurs, the unsigned int is generally used as the identification type of the for or while loop body. If a negative value is assigned to it, it will lead to a serious false loop! Pain! Pain!

 

Stay Away From traps and cherish your life! O (∩) O Haha ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.