I was thinking this morning here, what would be the fastest way to reverse a number of positive to negative and from negative to positive, of course, the simplest way might
Assuming the processor is at least somewhat competent and has sizeof(int) == sizeof(Cpu_register)
, then a "make this number negative" will be a single instruction (usually called neg
) [well, may need the value loading and storing too, but if you are using the variable for anything else, it can remain after the load, and only be stored later one...]
Multiplying by -1
is most likely slower than a = -a;
, but most competent compilers should be able to make both of these equivalent.
So, just write the code clearly, and the rest should take care of itself. Negating a number is not a difficult operation in most processors. If you are using some unusual processsor, then look at the compiler output, and see what it does.