Is it possible to differentiate between 0 and -0?

前端 未结 7 1449
鱼传尺愫
鱼传尺愫 2021-01-31 07:11

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 exam

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 07:26

    In the C++ language specification, there is no such int as negative zero.

    The only meaning those two words have is the unary operator - applied to 0, just as three plus five is just the binary operator + applied to 3 and 5.

    If there were a distinct negative zero, two's complement (the most common representation of integers types) would be an insufficient representation for C++ implementations, as there is no way to represent two forms of zero.


    In contrast, floating points (following IEEE) have separate positive and negative zeroes. They can be distinguished, for example, when dividing 1 by them. Positive zero produces positive infinity; negative zero produces negative infinity.


    However, if there happen to be different memory representations of the int 0 (or any int, or any other value of any other type), you can use memcmp to discover that:

    #include 
    
    int main() {
        int a = ...
        int b = ...
        if (memcmp(&a, &b, sizeof(int))) {
            // a and b have different representations in memory
        }
    }
    

    Of course, if this did happen, outside of direct memory operations, the two values would still work in exactly the same way.

提交回复
热议问题