简体   繁体   中英

C++ converting between unsigned integers and signed integers

Why does the following piece of code write B2 first and A1 then? Shouldn't it write both A1? Implicit datatype in C++ converts from signed int to unsigned int (higher in hierarchy)

short a=-5;
unsigned short b=-5u;
if(a==b)
    printf("A1");
else
    printf("B2");
// prints B2

int a2=-5;
unsigned int b2=-5u;
if(a2==b2)
    printf("A1");
else
    printf("B2");
return 0;

// prints A1

Casting negative signed integral type into unsigned always underflows and it yields modulo arithmetic. unsigned int x = (unsigned int)-1 stores UINT_MAX into x .

Example :

unsigned int x = (unsigned int) -1;
std::cout << x << std::endl;
x = (unsigned int) -5;
std::cout << x << std::endl;

outputs:

4294967295
4294967291

Note that both -1 and -5 have been converted into extremely high values, whose difference is equal to 4 as well.

for the given code

short a=-5;
unsigned short b=-5u;
if(a==b)
    printf("A1");
else
    printf("B2");

for an implementation where sizeof(short) < sizeof(int) , when a is promoted to int you get the -5 value preserved, and when b is promoted to int you get the 2 k - 5 value preserved, where k is the number of value representation bits in an unsigned short .

so, as int they're different, even though they may be the same short size bitpatterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM