2005-11-15

Optimal Integer Negation Strategy

I wonder what the best way to negate an integer value is. I can think of these:

int i, j;
i = 57;
j = i * (-1);
j = 0 - i;
j = -i;

In college George Ernst burned into my brain that adds are cheap and mults are expensive. That seems a tad too elementary to always be true. I'm hopeful that C compilers by now have evolved to the point where they can identify the negation and directly optimize it into a simple assembly instruction or six. What I do know is that there are worse ways to negate an integer.

No comments: