Home > OS >  How can I guarantee that a variable will never be zero without using a judgment statement in C?
How can I guarantee that a variable will never be zero without using a judgment statement in C?

Time:10-27

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.

CodePudding user response:

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 to 1.
If x!=0, !x will be 0 and y will be assigned to x.

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

CodePudding user response:

You should check the assembler output of your compiler. For example,the X86 architecture has an instruction called cmov (https://www.felixcloutier.com/x86/cmovcc) that is designed to handle this kind of thing without branches. The Arm architecture allows pretty much all instructions to be executed depending on CPU flags: https://developer.arm.com/documentation/dui0473/m/condition-codes/conditional-execution-in-arm-state.

Thus, when optimizations are enabled your compiler will likely produce no branches.

CodePudding user response:

Maybe you can do this just like you are doing it in perl: (void)((y = x) || (y = x 1));

CodePudding user response:

well you could always do (x * x) 1 a number squared can never be negative (unless imaginary) and if both equal zero the result would be 1

  •  Tags:  
  • c
  • Related