开发者

What is the difference between -1 and ~0

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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜