I'm just starting to teach myself C++, and have begun learning about integer overflow. Out of curiosity I wrote some tests just to see what occurs with certain integer values.
Here's my program:
#include <iostream>
int main()
{
int x(0);
std::cout << x << std::endl;
x = x + 2147483647;
std::cout << x << std::endl;
x = x + 1;
std::cout << x << std::endl;
std::cout << std::endl;
unsigned int y(0);
std::cout << y << std::endl;
y = y + 4294967295;
std::cout << y << std::endl;
y = y + 1;
std::cout << y << std::endl;
}
And here's the output:
0
2147483647
-2147483648
0
4294967295
0
The output surprised me a bit, and I'm wondering if someone could explain why this happened, OR if the unexpected-ness of these results is expected; so this may just be the result of my specific machine.
Integers (generally) take a 32-bit representation. If you have 32 bits, you can address from 0 to 231-1. i.e.,
00000000000000000000000000000000
00000000000000000000000000000001
.
.
.
01111111111111111111111111111111
^-------------------------------
signed bit
0 indicates a positive number, 1 indicates a negative number.
If you add 1 to 01111111111111111111111111111111
, you get 10000000000000000000000000000000
, which is -2147483648 in decimal.
Using an unsigned integer, there's no signed bit and, ipso facto, can have a number twice as large as your largest signed integer. However, when the number rolls over again (i.e., 11111111111111111111111111111111
+ 00000000000000000000000000000001
), you simply roll back to 00000000000000000000000000000000
.
For a more in depth understanding, you can look at two's complement, which is how integers are represented in computers.