What is the difference between -1 and ~0

2019-07-26 04:02发布

问题:

The title really says it all: what is the difference between minus one and tilda (ones-complement) zero?

The question came up during a discussion of the best way to specify a bit mask in which all bits are set. Which of the following is better?

int func(int value, int mask = -1) {
    return (value & mask);
}

or

int func(int value, int mask = ~0) {
    return (value & mask);
}

Are there any other uses where it would be the other way around?

Update: There has been a similar discussion on this topic over at stackoverflow.com/q/809227/34509 which I missed during my prior research. Thanks to Johannes Schaub for pointing it out.

回答1:

The first variant relies on 2's complement representation of negative numbers, which isn't necessarily used. 1's complement can be used too... or other encoding. My vote is for the second approach



回答2:

The second example is more clear as to what you're trying to test for.



回答3:

Both are same. Except that, -1 doesn go well with unsigned int without warning.