Likelihood of if statement and case

Richard Andrew Cattermole (Rikki) richard at cattermole.co.nz
Wed Sep 11 09:26:16 UTC 2024


Given the recent 
[thread](https://forum.dlang.org/post/mailman.2451.1724377685.3719.digitalmars-d@puremagic.com) by Manu, requesting a way to annotate likelihood for branches, I think I have found a way forward that is both in recognization of existing practices both in D and outside.

In this thread, Tejas provided a 
[link](https://blog.aaronballman.com/2020/08/dont-use-the-likely-or-unlikely-attributes/) that shows issues with the C/C++ design.

1. The true path of a branch is assumed to be unlikely.
2. The false path, or the fallthrough path if false path does not 
exist is assumed to be taken.
3. D's if statement, is if-else, not if-elseif-else based, 
therefore it inherently has a priority and scope awareness and 
does not need a priority to be defined by the user.
4. Switch statements have a priority for their cases by simply 
their order. The likely path is the default statement.

The unlikelihood is now defined against D using existing 
practices. No changes there.

What we want to define is a way to do a kind of swap, so to tell 
the compiler that no, the order in the code is the wrong way 
around.

```d
switch(e) {
     /*@likely*/
     case E.unlikely1:
         break;
     default:
         break;
}

if (e.unlikely1) /*@likely*/ {
} else {
}
```

``@likely`` would be defined in core.attributes. It requires 
minimal changes, but instead it requires us to explicitly define 
this behavior of priorities and likelihood.


More information about the dip.ideas mailing list