2 ms·
Not necessarily. A compiler can optimize ?x:0 into a multiply. For example, f(x) ? y : 0 can also be written as (int)(bool)f(x) * y
by colejohnson66 9y ago
Not necessarily. A compiler can optimize ?x:0 into a multiply. For example,
f(x) ? y : 0
can also be written as
(int)(bool)f(x) * y
- Atrix256 9y agoHere's a godbolt to play with as well, showing how it does actually compile down to being branchless in clang (you can switch it to use other compilers too) https://goo.gl/bywp8b https://goo.gl/bywp8b
- pjscott 9y agoIn case anybody was wondering, the x86 assembly is doing the multiply trick. The rather confusing "lea" instruction -- Load Effective Address -- is used as a space-efficient way of saying "take one register, multiply by 1, 2, 4, or 8, add another register, and put it in a third register". The thing in the register that gets multiplied by that constant is either a 1 or a 0. If the constants had been less convenient numbers, like 42, the compiler could have instead used a conditional move instruction -- more general-purpose, but I believe slightly larger and often ever-so-slightly slower.