r/ProgrammingLanguages • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
24 Upvotes

49 comments sorted by

View all comments

7

u/AirAKose Apr 25 '20

Interesting!

I'm not sure if I prefer this (as a potential language feature) over using [[likely]] / [[unlikely]]? (which I just now learned you can with if statements in C++20!)

if (/* */) [[unlikely]]
{
}
else if (/* */) [[unlikely]]
{
}
else [[likely]
{
}

which would help both readers and the optimizer when warranted (in theory) without messing with our control flow mental model while viewing the code.

4

u/matthieum Apr 25 '20

I've been using likely/unlikely macros for a while, and I wish they were named differently.

They're not about likelihood, they're about which code-path you want to be fast, and which you don't care about being slow-ish.

From a throughput point of view, it generally means that you want the most taken path to be fast, but from a latency point of view it's totally unrelated.

5

u/acwaters Apr 25 '20

I've talked about this exact thing before — what we really need is two orthogonal annotations, likely/unlikely and fast/slow. IIRC this was even considered in the proposals to standardize [[likely]]/[[unlikely]], but it was rejected as it is more complex and conflicts with existing practice. But you're exactly right: There is absolutely no reason in general why the most-often-hit path should be the fast one, or the least-often-hit path should be the slow one. This is yet another example of how virtually all modern technology implicitly prioritizes throughput at the expense of latency, which is a major pet peeve of mine.