1

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.

Community
  • 1
  • 1
zennehoy
  • 6,405
  • 28
  • 55

3 Answers3

8

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

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Ok, that makes sense. Though honestly, what architecture still uses anything other than 2's complement? And I believe java actually guarantees it? – zennehoy Jul 18 '11 at 14:26
  • The JVM does guarantee the int type to be a 32 bit two's complement number. – Edward Thomson Jul 18 '11 at 16:48
  • I think that both rely on two's complement (if you use `int`). We had this question previously http://stackoverflow.com/q/809227/34509 . In particular, the `~0` could end up being the value `0`, in which case it could end up being all bits zero when stored. Only on two's complement, the resulting bit pattern of `~0` will identify a unique value (-1) instead of a single value having two possible representations (negative/positive zero). So I think the only portable way is to use `unsigned int` and assign `-1` to it. – Johannes Schaub - litb Jul 19 '11 at 14:11
3

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

Bryan Boettcher
  • 4,412
  • 1
  • 28
  • 49
1

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

iammilind
  • 68,093
  • 33
  • 169
  • 336