Why do unsigned int x = -1 and int y = ~0 have the same binary representation?

前端 未结 5 1471
感动是毒
感动是毒 2020-12-15 09:54

In the following code segment what will be:

  • the result of function
  • value of x
  • value of y
    {
         unsigned int x=-1;         


        
5条回答
  •  时光说笑
    2020-12-15 10:14

    unsigned int x=-1;

    1 is an integer literal and has type int (because it fits in an int). Unary - applied to an int causes no further promotion so -1 is an int with value -1.

    When converted to an unsigned int modulo 2^N arithmetic is used where N is the number of value bits in an unsigned int. x has the value 2^N - 1 which is UINT_MAX (What's MAX_UNIT?).

    int y;
    y = ~0;
    

    Again 0 is type int, in C all the allowed representations of int must have all the value bits of an int representing 0 as 0. Again no promotion happens for unary ~ so ~0 is an int with all value bits being 1. What it's value is is implementation dependent but it is negative (the sign bit will be set) so definitely neither of UINT_MAX or INT_MAX. This value is stored in y unchanged.

    if(x == y)
        printf("same");
    else
        printf("not same");
    

    In this comparison y will be converted to unsigned int in order to be compared with x which is already an unsigned int. As y has an implementation value, the value after conversion to unsigned int is still implementation defined (although the conversion itself is modulo 2^N and fully specified). The result of the comparison is still implementation defined.

    So in conclusion:

    implementation defined, UINT_MAX, implementation defined

    In practice on ones' complement:

    not same, UINT_MAX, -0 (aka 0)

    sign plus magnitude:

    not same, UINT_MAX, INT_MIN

    two's complement:

    same, UINT_MAX, -1

提交回复
热议问题