Hacker News new | past | comments | ask | show | jobs | submit login

Ternary isn't the same as a branch and you want your this simple comparison function to get inlined every time



> Ternary isn't the same as a branch

It should be. The C ternary is just an expression-oriented version of if/elseif/else.

Languages with a functional bend simply make if/elseif/else an expression in the first place e.g. in Rust it'd be

      return 
        if a < b { Ordering::Less }
        else if a > b { Ordering::Greater }
        else { Ordering::Equal }
Though obviously that specific version is an overly complex way of writing:

    return a.cmp(b);


Most compilers will probably reduce if-else and ternary to the same instructions. If it's a conditional value binding it might not be a branch but a conditional move instruction.


i find it really odd that of all the knocking back and forth on this thread, you are the only person to suggest that using symbolic values for 'greater than', etc, improves readability.


It's not really my suggestion though, it's just what Rust does (inherited from Haskell, interestingly enough OCaml does not do that) and I figured I'd post "proper" rust code rather than a bastardisation.


If you need to optimize to that extent, then do whatever you need to do. In the vast majority of applications it makes no difference.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: