Is this:
int val;
// ...
val = (val != 0) ? otherVal : 0;
less efficient than this:
int val;
//...
if (val != 0)
val = otherVal;
?
Are compiler able to optimize the ternary operator? The intent is clear, is there any way it could be wanted to actually write 0 to memory? Maybe when memory is mapped to a file?
Can we assume it doesn't matter?
EDIT: The point is to set a variable to some value if one condition is met. There is no wanted else branching. which is why I ask if a ternary (with obligatory else branch that is supposed to make a copy) will be less efficient or optimized.
Mats Petersson suggestion is generally the best "Write the most readable variant". However, if you are trying to write optimal speed performance code, you need to know more info about your computer and processor. With some machines, the first will run faster (highly pipelined processors: no branching, optimized ternary operator). Other machines will run quicker with the second form (simpler).
You could use a branchless ternary operator, sometimes called bitselect ( condition ? true : false).
Don't worry about the extra operations, they are nothing compared to the if statement branching.
bitselect implementation:
inline static int bitselect(int condition, int truereturnvalue, int falsereturnvalue)
{
return (truereturnvalue & -condition) | (falsereturnvalue & ~(-condition)); //a when TRUE and b when FALSE
}
inline static float bitselect(int condition, float truereturnvalue, float falsereturnvalue)
{
//Reinterpret floats. Would work because it's just a bit select, no matter the actual value
int& at = reinterpret_cast<int&>(truereturnvalue);
int& af = reinterpret_cast<int&>(falsereturnvalue);
int res = (at & -condition) | (af & ~(-condition)); //a when TRUE and b when FALSE
return reinterpret_cast<float&>(res);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With