Search code examples
c#signed

Why is Negative Zero equal to Positive Zero?


In computer programming, there exists a positive and negative zero. This may not come as a shock to you, but what is odd is the apparent fact that positive zero is equal to negative zero. Here is an example:

public static class Program
{
    public static void Main()
    {
        int positive = 0;
        int negative = -0;
        Console.WriteLine(positive == negative);
        Console.Read();
    }
}

Output shows as "True".

As for everyone apparently flooding comments with "Int defaults to 0." I should point out that float's and doubles do the same thing, returning true for equality amongst negative and positive zero.

I suppose this may have something to do with the concept of graphing, which negative and positive zero would exist orthographically within the same dimensional point. Or is there another reason for the equality between them?


Solution

  • A negative int is done using two's complement. That is, invert the bits and add one. Regardless of the bit length, if you do this with a zero value, you get zero back.

    For example 0000 flipped becomes 1111 and adding 1 rolls over back to 0000.

    This is by design to eliminate the redundancy of having two zeroes.

    With float and double, according to IEEE-754 there are technically both +0 and -0, but they are considered equal.