Branchless Programming: Difference between revisions

Line 47: Line 47:


Rather than doing
Rather than doing
<syntaxhighlight lang="python">
<syntaxhighlight lang="cpp">
if age > 10:
if (age > 10) {
   x = x + 10
   x += 10;
else:
} else {
   x = x - 10
   x -= 10;
}
</syntaxhighlight>
</syntaxhighlight>
you can do
you can do
<syntaxhighlight lang="python">
<syntaxhighlight lang="cpp">
x = x + (20 * (age > 10) - 10)
x = x + (20 * (age > 10) - 10);
# or
# or
y = age > 10
y = age > 10;
x = x + 10 * y - 10 * (1-y)
x = x + 10 * y - 10 * (1-y);
</syntaxhighlight>
</syntaxhighlight>


Similarly, instead of doing
Similarly, instead of doing
<syntaxhighlight>
<syntaxhighlight lang="cpp">
if age > 10:
if (age > 10) {
   x+=1
   x++;
}
</syntaxhighlight>
</syntaxhighlight>
you can just write <code>x += age>10</code>.
you can just write <code>x += age>10</code>.