int max = ~0; What does it mean?

前端 未结 8 2006
灰色年华
灰色年华 2021-01-19 03:46

int max = ~0;

What does it mean?

8条回答
  •  再見小時候
    2021-01-19 04:29

    The ~ operator is the unary bitwise complement operator which computes the bitwise complement. This means that it reverses all the bits in its argument (0s become 1s and 1s become 0s). Thus,

    int max = ~0;
    

    which is setting max to the negation of the 32-bit value 0000 0000 0000 0000 0000 0000 0000 0000 resulting in 1111 1111 1111 1111 1111 1111 1111 1111. As we are storing this result in an Int32, this is the same as -1.

    Whether or not it is better to say

    int max = ~0;
    

    or

    int max = -1;
    

    depends on the context. If the point of max is to have a number all of whose bits are 1 I would choose the former. If the point of max is to compute the maximum of a list of non-negative integers, I would choose the latter (well, I'd prefer int max = Int32.MinValue; and even more so, I'd just prefer int max = list.Max();).

提交回复
热议问题