Johnny Pauling
Johnny Pauling

Reputation: 13387

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

Upvotes: 0

Views: 364

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

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 2k - 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.

Upvotes: 1

LihO
LihO

Reputation: 42085

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.

Upvotes: 2

Related Questions