Search code examples
ccompiler-optimizationmicro-optimization

How can I guarantee that a variable will never be zero without using a conditional statement in C?


For example, Let's say a variable x, x could be anything include 0.
Then we got code like:

if(x==0) {
    y = 1;
}
else {
    y = x;
}

Could I do this without producing branches in C/C++?

I'm trying to optimize a piece of code. I want to remove branches as much as possible. There are similar judgments, so I want to convert them into statements without branches to make the code as efficient as possible.


Solution

  • Some general notes:

    1. As mentioned in other comments, some compilers can optimize and eliminate the branch. You can check the assembly output (e.g. in Godbolt) to make sure.
    2. Beware of premature optimizations.
    3. Always measure and make sure your speculation about what's taking up time is correct.

    Having said that you can try the following "trick":

    y = !x + x;
    

    Assuming x,y are integer types:

    • If x==0, !x will be 1 and y will be assigned the value 1.
    • If x!=0, !x will be 0 and y will be assigned the value x.

    Note: see @CostantinoGrana's comment below about the guarantee in the standard. You can also verify it in your specific environment (compiler etc.).