Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it that an unsigned integer array can contain a negative integer?

I wrote this piece of code just to see what would happen if I put a negative integer into an unsigned integer array.

#include <iostream>

int main()
{
    using namespace std;

    unsigned int array[4];
    array[0]=4;
    array[1]=4;
    array[2]=2;
    array[3]=-2;

    cout << array[0] + array[1] + array[2] + array[3] << endl;

    unsigned int b;
    b=-2;
    cout << b <<endl;

    return 0;
}

I was expecting integer overflow to occur in both the cases. However, only in the second case that actually happened. In the first case, everything behaved as if it were an oridinary integer array, not an unsigned integer array. So what exactly is happening that's causing this anomalous behaviour. My compiler is gcc 4.8 in cases that's of any importance. Thank you for your help. EDIT: Here's th output on my computer

8
4294967294
like image 277
sayantankhan Avatar asked Aug 30 '25 17:08

sayantankhan


1 Answers

There is an integer overflow. Here is the reason ( the numbers are converted to unsigned int)

 1111 1111 1111 1111 1111 1111 1111 1110 // -2
+0000 0000 0000 0000 0000 0000 0000 0100 //+ 4
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 0010 //= 2
+0000 0000 0000 0000 0000 0000 0000 0100 //+ 4
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 0110 //= 6
+0000 0000 0000 0000 0000 0000 0000 0010 //+ 2
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 1000 //= 8 -> the result
like image 63
okaerin Avatar answered Sep 02 '25 11:09

okaerin