Search code examples
c++unsigned-integer

assigning an unsigned value to integer data type


I wrote code:

int a = -1U;
cout << a;

Why the output is -1 not 2^w-1?

As in the case of:

long long a = -1U;
cout << a;

The output comes out as
4294967295


Solution

  • -1U is the negation of 1U. As an unsigned cannot have a negative value the result is incremented by (UINT_MAX + 1). Result UINT_MAX is 4294967295 on OP's machine.

    In both of OP's cases, code is initializing a signed integer variable with 4294967295u.


    int a = -1U;
    

    Why the output is -1 not 2^w-1?

    2w - 1 (w being the bit width 32) is outside the range of int a so a cannot have that value.

    Assigning an out-of-range value to an int results in implementation defined behavior. On OP's machine, assigning 4294967295 to an int "wrapped" to -1.


    long long a = -1U;
    

    long long a = -1U; is like long long a = 4294967295; (see above), so a has the value of 4294967295, well within the long long range.