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.
Some general notes:
Having said that you can try the following "trick":
y = !x + x;
Assuming x
,y
are integer types:
x==0
, !x
will be 1
and y
will be assigned the value 1
.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.).