Comparison between the number of unsigned characters and the number of signed characters

Source: Internet
Author: User

Let's take a few questions and explain why the answer is like that.

Question 1:

Int A =-1;

Unsigned int B = 1;

Printf ("% d", A> B );

Result output: 1

Because when comparing the number of unsigned symbols with the number of signed symbols, You need to convert the number of signed symbols to the number of unsigned ones, and then compare them. After a is converted to an unsigned number, it is 0 xffffffff. It must be greater than B.

Question 2:

Char A =-1;

Unsigned char B = 1;

Printf ("% d", A> B );

Result output: 0

Strange. How can this happen? This is because the two are converted to int. If a is converted to int, it indicates-1. If B is converted to int, it means 1. The former is smaller than the latter. Note that it is not as simple as converting Char to unsigned char as in question 1.

Question 3:

Int A =-1;

Unsigned char B =-1;

Printf ("% d \ n", a <B );

Result output: 1

The reason is that we need to convert B to int, that is, 0xff is greater than-1.

Question 4:

Char A =-1;

Unsigned int B =-1;

Printf ("% d \ n", A = B );

Result output: 1

The reason is that the char type is extended to the unsigned int and is equal to B, and the same as 0 xffffffff.

 

The following are some of my conclusions:

The size of the unsigned int to be compared with that of the signed Int.

When the int type is compared with the non-Signed int type, the non-Signed int type is converted to the int type for comparison.

When the unsigned int type is compared with other types such as unsigned short, signed short, and unsigned char and char, all other types are converted to the unsigned int type for comparison.

Non-Unsigned int and non-int types such as unsigned short, signed short, unsigned char, and Char are converted to int type for comparison.

 

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.