What is the purpose of “int mask = ~0;”?

前端 未结 6 663
春和景丽
春和景丽 2020-12-29 18:30

I saw the following line of code here in C.

 int mask = ~0;

I have printed the value of mask in C and C++. It always prints

6条回答
  •  醉酒成梦
    2020-12-29 18:51

    C and C++ allow 3 different signed integer formats: sign-magnitude, one's complement and two's complement

    ~0 will produce all-one bits regardless of the sign format the system uses. So it's more portable than -1

    You can add the U suffix (i.e. -1U) to generate an all-one bit pattern portably1. However ~0 indicates the intention clearer: invert all the bits in the value 0 whereas -1 will show that a value of minus one is needed, not its binary representation

    1 because unsigned operations are always reduced modulo the number that is one greater than the largest value that can be represented by the resulting type

提交回复
热议问题