Search code examples
c++mathintegersignedinteger-overflow

C/C++ Negating a integer type variable with a value of 0


I want to pass the sign changed version of some value to a function. I know how to check for overflow if the sign changes however I don't know about this one case.

int apple( int );

int a = 0;

apple( -a );

Is that defined behavior covered by the C/C++ standard? I'm passing -0 I would guess when a == 0. What about using something like this instead: a ? -a : a ? Thanks


Solution

  • -a for the case of a == 0 is well defined. What the standard requires is that it's still zero.

    It does not guarantee that the "bits" in the value are unchanged (they are for two's complement, but not for ones complement, in which case the value is "negative zero", whatever the bit pattern of that is). But the value should be true for if (!x) or if (x == 0), even if x has the value "negative zero" - it's up to the compiler and/or processor manufacturer to make sure that works.