Unsigned integer in C ++

I am writing the following code:

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

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

      

The output is the meaning of garbage, which is understandable.
Now I am writing the following code:

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

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

      

The result is now 3. What's going on here? How is the garbage cost added by 5 here?

+3


source to share


1 answer


Think of the values unsigned int

drawn on the large edge of the counter with the largest possible value (UINT_MAX), near zero.

Subtracting 3 from 1 moves you 3 spaces back (which gives you UINT_MAX - 1), and adding 5 to that moves you 5 spaces forward.



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

on your platform.

Note that the well-defined nature of this overflow is incorrect for types signed

. Type overflow behavior signed

is undefined in C ++.

+6


source







All Articles