top | item 38803525

(no title)

Kwantuum | 2 years ago

Surely this was meant to be cnt += a[i] > 0

discuss

order

amelius|2 years ago

But a[i] > 0 can still compile to a branch, depending on the compiler.

dkersten|2 years ago

Really? In what case? It’s just an expression and the entire statement just uses the expression result.

Of course when optimising code like this, I think it’s important to look at the generated assembly anyway and then you can be sure that it does what you expect on the compilers you intend on supporting (doubly so when you want to generate conditional moves — I’ve found that to be a bit of a puzzle where I sometimes need to move things around as the obvious code still generated a branch), but at least GCC and Clang won’t generate a branch for using just a comparison. Maybe it’s not the compiler and instead the target architecture? In x86, comparisons set flags, so by themselves aren’t branches. In any case, I recommend using compiler explorer when working on code where this matters.

avianlyric|2 years ago

Can it? I understand it’s always possible to decompose that to

if (a[i] > 0) return 1 else return 0 end

But why would a compiler do that?

Comparison operations are basic primitives that usually store their result into a register. With branching comparison operators potentially also available, but if there’s a branching comparator operation in your ISA, then there’s almost certainly also a pure comparator operation in your ISA, because you can always compose a branching comparator from simple comparison operation followed by a basic equality comparison of the result.

So I guess my question is, while it’s technically possible for a compiler to compile this into a branching operations, under what circumstances would a compiler actually choose to do that, given there’s isn’t a clear benefit?