Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it useful to write "0 - x" rather than "-x"?

I've occasionally noticed some C code insisting on using 0 - x to get the additive complement of x, rather than writing -x. Now, I suppose these are not equivalent for types smaller in size than int (edit: Nope, apparently equivalent even then), but otherwise - is there some benefit to the former rather than the latter form?

like image 833
einpoklum Avatar asked Mar 02 '23 12:03

einpoklum


2 Answers

tl;dr: 0-x is useful for scrubbing the sign of floating-point zero.

(As @Deduplicator points out in a comment:)

Many of us tend to forget that, in floating-point types, we have both a "positive zero" and a "negative zero" value - flipping the sign bit on and off leaves the same mantissa and exponent. Read more on this here.

Well, it turns out that the two expressions behave differently on positive-signed zero, and the same on negative-signed zero, as per the following:

value of x value of 0-x value of -x
-.0 0 0
0 0 -.0

See this on Coliru.

So, when x is of a floating-point type,

  • If you want to "forget the sign of zero", use 0-x.
  • If you want to "keep the sign of zero", use x.

For integer types it shouldn't matter.


On the other hand, as @NateEldredge points out the expressions should be equivalent on small integer types, due to integer promotion - -x translates into a promotion of x into an int, then applying the minus sign.

like image 137
einpoklum Avatar answered Mar 05 '23 17:03

einpoklum


There is no technical reason to do this today. At least not with integers. And at least not in a way that a sane (according to some arbitrary definition) coder would use. Sure, it could be the case that it causes a cast. I'm actually not 100% sure, but in that case I would use an explicit cast instead to clearly communicate the intention.

As M.M pointed out, there were reasons in the K&R time, when =- was equivalent to -=. This had the effect that x=-y was equivalent to x=x-y instead of x=0-y. This was undesirable effect, so the feature was removed.

Today, the reason would be readability. Especially if you're writing a mathematical formula and want to point out that a parameter is zero. One example would be the distance formula. The distance from (x,y) to origo is sqrt(pow(0-x, 2), pow(0-y, 2))

like image 34
klutt Avatar answered Mar 05 '23 18:03

klutt