Re:Do I Really Need a Programming Language?
by carlob on Sunday December 29, 2013 @04:42AM
(#6979022)
The overly eager optimizer in me was thinking:
yay! no branching!
[ Parent
| on HN ]
Re:Do I Really Need a Programming Language?
by delinka on Sunday December 29, 2013 @05:28AM
(#6979113)
Iff in your language of choice a Boolean is always converted to a 1 or 0. In C, at least, that's not necessarily the case.
That said, I'm always looking for the least branchy way of doing things.
Re:Do I Really Need a Programming Language?
by dbaupp on Sunday December 29, 2013 @05:42AM
(#6979149)
I was under the impression that the C standard does mandate that comparisons give 1 and 0 for true and false. (Other nonzero things are considered true, but a plain comparison won't return them.)
Re:Do I Really Need a Programming Language?
by userbinator on Sunday December 29, 2013 @08:56AM
(#6979522)
It does.
ISO/IEC 9899:1999, 6.5.8, p6 has this to say:
"Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int."
Re:Do I Really Need a Programming Language?
by Evgeniuz on Sunday December 29, 2013 @06:19AM
(#6979235)
(((price - 100) / abs(price - 100)) * 25 + 75) / 10
Here you go, simple integer math, no programming necessary :) That said, this isn't optimisation, multiplication and division aren't intrinsically better than branching.
Re:Do I Really Need a Programming Language?
by carlob on Sunday December 29, 2013 @10:59AM
(#6979935)
x/abs(x) is really sign, which is something you can implement using bitwise oprations.
Your solution fails when price == 100 as sibling pointed out.
Re:Do I Really Need a Programming Language?
by jonsen on Sunday December 29, 2013 @07:33AM
(#6979380)
if (price == 100){ ...
Re:Do I Really Need a Programming Language?
by praptak on Sunday December 29, 2013 @05:40AM
(#6979137)
Does it compile to a piece of code without any conditional jumps?
It's not uncommon for machines to have a branchless idiom for generating the value of a condition. For instance, in x86:
cmp price, 100
setg reg
movzx reg, reg
lea reg, [reg + reg*4 + 5]
Re:Do I Really Need a Programming Language?
by userbinator on Sunday December 29, 2013 @09:01AM
(#6979531)
cmp price, 100
cmc
salc
and al, 5
add al, 5
6 bytes not including comparison. "You don't get into the demoscene, the demoscene gets into you." :)