Standard way to supply hints to branches

Quirin Schroll qs.il.paperinik at gmail.com
Fri Sep 13 09:54:47 UTC 2024


On Wednesday, 11 September 2024 at 11:05:03 UTC, Dom DiSc wrote:
> On Wednesday, 11 September 2024 at 08:53:30 UTC, ShadoLight 
> wrote:
>> Just tongue-in-cheek along these lines ;-)
>>
>> iffy(...) ...;
>> else ...;
>>
>>
>> At least it is shorter!
>
> In german it would be easy: "wenn" is the likely path, "falls" 
> is the unlikely path.

There’s also _when_ in English. Being German myself, I found 
_wenn_ and _falls_ are way more interchangeable than English _if_ 
and _when._ What teachers tell you isn’t that clear cut true. 
Haskell has a `when` function for monads.

Maybe we could add `unless` which is a negated `if`, but 
`unless(cond)` is different from `if (!cond)` in how it’s seen my 
the optimizer. CoffeScript has `unless`. However, I still think 
any optimization hints should be in a form that allows a 
conforming compiler to ignore it, i.e. a `pragma` is ideal:

```d
if (x is null) pragma(unlikely) return 0;
// use *x
```

The best thing about `pragma` is that it allows for additional 
arguments. For example, a `bool` to enable or disable it: 
`pragma(unlikely, false)` could be as if it’s not there. Great 
for meta-programming. For `pragma(likely)`, a numerical 
probability makes sense, too: `pragma(likely, 0)` is equivalent 
to `pragma(unlikely)` and a single `pragma(likely, value)` (with 
`value` > 0) is `pragma(likely)`.

Generally speaking, if there are more than two branches, with two 
or more of them tagged `likely`, they can be given weights, that 
may be derived from abstract reasoning or profiling. That’s 
essentially what GCC has with 
`__builtin_expect_with_probability`, except that it’s with 
weights and not probabilities.


More information about the Digitalmars-d mailing list