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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With