Question

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

Was it helpful?

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.

OTHER TIPS

Negating an integer with the value 0 yields 0. There's no need for any special handling.

As in maths, in C++ -0 == 0.

Even though an implementation is allowed to use ones' complement (and thus there can be bits patterns for both 0 and -0) this doesn't change the meaning of the value and any additional computations necessary to handle the specific -0 case would be a mere implementation detail and would be totally transparent to you as a programmer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top