Is it possible to differentiate between 0 and -0?

Filip Minx picture Filip Minx · Apr 30, 2015 · Viewed 7.9k times · Source

I know that the integer values 0 and -0 are essentially the same. But, I am wondering if it is possible to differentiate between them.

For example, how do I know if a variable was assigned -0?

bool IsNegative(int num)
{
    // How ?
}

int num = -0;
int additinon = 5;

num += (IsNegative(num)) ? -addition : addition;

Is the value -0 saved in the memory the exact same way as 0?

Answer

Marco A. picture Marco A. · Apr 30, 2015

It depends on the machine you're targeting.

On a machine that uses a 2's complement representation for integers there's no difference at bit-level between 0 and -0 (they have the same representation)

If your machine used one's complement, you definitely could

0000 0000   -> signed   0 
1111 1111   -> signed   −0

Obviously we're talking about using native support, x86 series processors have native support for the two's complement representation of signed numbers. Using other representations is definitely possible but would probably be less efficient and require more instructions.

(As JerryCoffin also noted: even if one's complement has been considered mostly for historical reasons, signed magnitude representations are still fairly common and do have a separate representation for negative and positive zero)