4

I write the following code:

 #include <iostream>
using namespace std;
int main() {

   unsigned int i=1;
   i=i-3;
   cout<<i;
   return 0;
}

The output is a garbage value, which is understandable.
Now I write the following code:

    #include <iostream>
    using namespace std;
    int main() {

    unsigned int i=1;
    i=i-3;
    i=i+5;
    cout<<i;
    return 0;
}

Now the output is 3. What's happening here? How is the garbage value being added by 5 here?

metasj
  • 65
  • 1
  • 7
  • 12
    it's not garbage, the value underflows round to unsigned int max value - 2, you then added 5 to this so it becomes positive 3 – EdChum Apr 11 '17 at 12:59
  • 1
    Look it up: https://en.wikipedia.org/wiki/Two%27s_complement – Meccano Apr 11 '17 at 13:00
  • Unsigned integers overflow in a well-defined manner (unlike signed integers). Related questions: http://stackoverflow.com/questions/16056758/c-c-unsigned-integer-overflow, http://stackoverflow.com/questions/9193880/overflowing-of-unsigned-int – Fabio says Reinstate Monica Apr 11 '17 at 13:02

1 Answers1

7

Think of the values of unsigned int being drawn on a large clock face with the largest possible value (UINT_MAX) being next to zero.

Subtracting 3 from 1 moves you 3 places back on the clock (which gives you UINT_MAX - 1), and adding 5 to this moves you 5 places forward.

The net effect is to add 2 to 1, but it's important to know that the intermediate value is perfectly well defined by the C++ standard. It is not garbage, but related to the value of UINT_MAX on your platform.

Note that the well-defined nature of this overflow is not true for signed types. The behaviour on overflowing a signed type is undefined in C++.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Should I consider the difference between 0 and INT_MAX 1? – metasj Apr 11 '17 at 13:09
  • 1
    Did you mean UINT_MAX? If so then consider the difference between 0 and UINT_MAX to be -1. You're then consistent with unsigned arithmetic. Assigning a value of `-1` to an `unsigned` type is defined to yield UINT_MAX. – Bathsheba Apr 11 '17 at 13:11
  • Yeah UINT_MAX. I referred 1 to be the absolute difference between 0 and UINT_MAX.It is clear now. – metasj Apr 11 '17 at 13:13