DanB DanB - 1 month ago 4
C Question

C evaluation based on boolean - which is faster, which is better style?

It seems that in general, in C (and many other languages) one could equally well do, e.g.:

if (x > 0){
y = value1;
}
else{
y = value2;
}


or

y = (x>0)*value1 + (x <= 0)*value2;


The first case seems stylistically better because it's easier to read (for most people?). But then again the second case is more compact. More importantly, is there any difference in performance? It seems that the second case may be slower since both boolean expressions are evaluated, and there is a multiplication by zero.. but then, I vaguely recall that if statements have some small additional overhead? I realize I could actually measure the speed, but hoping someone has a more general answer.

Answer
y = (x>0)*value1 + (x <= 0)*value2;

This is terrible code, and shouldn't be written (you'd need to be 100% sure that the comparison operators return 1 for "true"; whether that's the case is subject to a lot of things).

That's what the ternary operator in C-alike languages is for:

 y = (x > 0) ? value1 : value2;

More importantly, is there any difference in performance?

I'd love to have an argument on "importance", but:

no. The ternary operator should expand to the same bytecode as the if construct, if the compiler is worth anything. Your y=(cond)*a+(!cond)*b construct is more probable to be slower, because of the strange abuse of multiplication; but then again, modern, optimizing compilers might kill that, anyway.

Comments