Doubt Branchless code
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Wed Apr 8 01:10:39 UTC 2026
On 08/04/2026 12:18 PM, matheus wrote:
> On Tuesday, 7 April 2026 at 23:48:37 UTC, Richard (Rikki) Andrew
> Cattermole wrote:
>> On 07/04/2026 7:08 AM, matheus wrote:
>>> Hello,
>>>
>>> Back in C days I used to write code with function pointer to avoid
>>> writing branches inside loops,
>>>
>>> To avoid this:
>>>
>>> for(;;){
>>> if(opt == 1){ func_1(); }else{func_2()};
>>> }
>>> Or maybe using switch if there were more options...
>>>
>>> So I used to do:
>>>
>>> if(opt == 1){ fp = &func_1(); }else{ fp = &func_2()};
>>>
>>> for(;;){
>>> fp();
>>> }
>>>
>>>
>>> I would like to know if there is a different way of doing that in D
>>> during RT execution and dynamic change of function execution before
>>> the loops?
>>>
>>> Thanks in advance,
>>>
>>> Matheus.
>>
>> How I typically do it:
>>
>> ```d
>> void outer() {
>> void inner(bool a, bool b)() {
>> for(;b;) {
>> static if (a) {}
>> }
>> }
>>
>> if (cond1 && !cond2)
>> inner!(true, false);
>> else if (cond2 && !cond1)
>> inner!(false, true);
>> else if (cond1 && cond2)
>> inner!(true, true);
>> else
>> inner!(false, false);
>> }
>> ```
>
> But this is CT, my problem was to this during RT.
>
> Thanks anyway for responding,
>
> Matheus.
It is optimizing RT, but we use CT to factor out the conditionals.
I've done this specifically when I would otherwise have RT if statements
in loops.
More information about the Digitalmars-d-learn
mailing list