Suppose I want to change the value of a variable when a flag is set. An obvious method is the following.
int a = 1, b = 2;
if(Flag)
{
a=b;
Flag = false;
}
This, however, is quite inefficient WRT the code generated to perform the operation. I have found that the following generates 40% less code to perform the operation.
a = ((!Flag)*a)+((Flag)*b);
Flag = false;
My question: I would rather not use the multiply “*” operator as multiplicative/division operators are slower to execute on my target. What else could I use to speed this up without increasing code space?
EDIT: The target device is an MSP430 running in the kHz range. code space and execution time are critical. the compiler is IAR C
The following achieves your desired logic without using multiply or any conditionals:
So when Flag==1 you get
and when Flag==0 you get
(You don’t really need a separate variable for mask either.. you can just do
--Flagand useFlaginstead ofmask, I just thought it’d make the solution a little clearer.)