-7

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;
}
  • 7
    Perhaps you need to learn about [two's complement](https://en.wikipedia.org/wiki/Two's_complement)? – Some programmer dude Sep 01 '17 at 16:10
  • 1
    What did you expect? A `unsigned` can't hold negative numbers, so 'all bits 1' will be a large number, whereas with a `signed` it will not (hint: sign bit, two's complement). What is your specific question? – Jesper Juhl Sep 01 '17 at 16:12
  • just want to know that why in case of int it is not giving -2147483647 which is 111.... 32 times – Rahul Verma Sep 01 '17 at 16:31
  • Here it's just remember that Int has also + values (not only minus) so half of it is -, other half +. What is well explained with two's complement mentioned by SPD. – Guillotine Sep 01 '17 at 17:27
  • @Rahul Verma "just want to know that why in case of int it is not giving -2147483647" - as already mentioned, read up on [two's complement](https://en.m.wikipedia.org/wiki/Two's_complement). – Jesper Juhl Sep 01 '17 at 18:02

1 Answers1

2

The ~ operator inverts all bits in the operand. Here, x starts out as 0. So assuming an int is 4 bytes wide it has the following binary representation:

00000000 00000000 00000000 00000000

When all bits are inverted you get:

11111111 11111111 11111111 11111111

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:

10000000 00000000 00000000 00000001
dbush
  • 205,898
  • 23
  • 218
  • 273