xyz
xyz

Reputation: 403

Wrap around range of unsigned int in C++?

I am going through C++ Primer 5th Edition and am currently doing the signed/unsigned section. A quick question I have is when there is a wrap-around, say, in this block of code:

unsigned u = 10;
int i = -42;
std::cout << i + i << std::endl; // prints -84
std::cout << u + i << std::endl; // if 32-bit ints, prints 4294967264

I thought that the max range was 4294967295 with the 0 being counted, so I was wondering why the wrap-around seems to be done from 4294967296 in this problem.

Upvotes: 0

Views: 2837

Answers (3)

James Adkison
James Adkison

Reputation: 9602

Given unsigned int that is 32 bits you're correct that the range is [0, 4294967295].

Therefore -1 is 4294967295. Which is logically equivalent to 4294967296 - 1 which should explain the behavior you're seeing.

Upvotes: 1

Peter
Peter

Reputation: 36607

Unsigned arithmetic is modulo (maximum value of the type plus 1).

If maximum value of an unsigned is 4294967295 (2^32 - 1), the result will be mathematically equal to (10-42) modulo 4294967296 which equals 10-42+4294967296 i.e. 4294967264

Upvotes: 5

Yu Hao
Yu Hao

Reputation: 122423

When an out-of-range value is converted to an unsigned type, the result is the remainder of it modulo the number of values the target unsigned type can hold. For instance, the result of n converted to unsigned char is n % 256, because unsigned char can hold values 0 to 255.

It's similar in your example, the wrap-around is done using 4294967296, the number of values that a 32-bit unsigned integer can hold.

Upvotes: 3

Related Questions