The below code gives output -1
.
#include <iostream>
using namespace std;
int main()
{
int x=0;
cout<<~x;
return 0;
}
But when I do the following modifications the answer changes to 4294967295
.
just want to know that why in case of int it is not giving -2147483647
which is 111.... 32 times
#include <iostream>
using namespace std;
int main() {
unsigned int x=0;
cout<<~x;
return 0;
}
The
~
operator inverts all bits in the operand. Here,x
starts out as 0. So assuming anint
is 4 bytes wide it has the following binary representation:When all bits are inverted you get:
Assuming two's complement representation of integers, the value of this bit sequence is -1. Note that if you add 1 to this value all bits become 0 (i.e. -1 + 1 = 0).
In contrast, a value of -2147483647 has the following representation: