0
    #include <iostream>

using namespace std;

int main()
{
    unsigned int x = 0;
    cout << x - 1;

    return 0;
}

The following code demonstrates printing, 4294967295. However, maybe I am forgetting math here but, 0 + -1 should be 0000 0000 0000 0000 0000 0000 0000 0000 (0) + 1111 1111 1111 1111 1111 1111 1111 1111 (-1), however how does this then map to 1000 0000 0000 0000 0000 0000 0000 0000 (4294967295)

Joe
  • 23
  • 4
  • 4294967295 is all-1's in binary (if you are interpreting the bits as a 4-byte unsigned int... OTOH if you are interpreting the bits as a 4-byte signed int, then all-1's is equal to -1). Unsigned math works pretty much like an analog odometer on a car, albeit an odometer where each dial has only 0 and 1 on it) – Jeremy Friesner Jun 22 '21 at 03:09
  • I see sorry my mistake, is it defined somewhere in binary mathematics that all 0's minus 1 will wrap it backwards to all 1's? I assumed it would stay all 0's, but I guess that would be strange behaviour if 0 - 1 is 0. – Joe Jun 22 '21 at 03:18
  • I don't think it's inherent in mathematics, it's just that all the computer manufacturers decided to represent unsigned integers the same way (probably because it was simplest and easiest to do it that way), and then the C and C++ languages adopted the hardware's behavior. See the Unsigned column of the "Comparison table" section of the wikipedia article for a quick demonstration of how unsigned 4-bit numbers work (32-bit numbers work the same, but the table would be too big to fit on the page :) ): https://en.wikipedia.org/wiki/Signed_number_representations#Comparison_table – Jeremy Friesner Jun 22 '21 at 03:30
  • 1
    @JeremyFriesner wrap-around behavior is just like congruence in math, or modulo operation – phuclv Jun 22 '21 at 05:51

0 Answers0