Below we make x = to 65535, in the first expression, we add 1 to x giving us 65536 which equals 1 0000 0000 0000 0000 in binary, making it wrap around and cause a overflow and now x will = zero. In the second expression we take the same variable x which now equals 65536 but prints as if x is = to 0, and then we subtract the 65535 from it and add it right back. x then prints out 65536.
I am a bit newer to this, could anyone explain why the second expression does not give an overflow?
- Code: Select all
using namespace std;
unsigned short x = 65535; // largest 2-byte unsigned value possible
cout << "x was: " << x << endl;
x = x + 1; //We add 1 to 65535 which gives an overflow.
cout << "x is now: " << x << endl;
//Subctract 66535 from x and then add it back to x
cout << "Bypass the overflow: "; x = x - 65535; cout << x + 65535; cout << endl;