C function taking two function pointers that share calculation

jmh530 john.michael.hall at gmail.com
Wed Sep 14 17:23:47 UTC 2022


There is a C library I sometimes use that has a function that 
takes two function pointers. However, there are some calculations 
that are shared between the two functions that would get pointed 
to. I am hoping to only need to do these calculations once.

The code below sketches out the general idea of what I've tried 
so far. The function `f` handles both of the calculations that 
would be needed, returning a struct. Functions `gx` and `gy` can 
return the field of the struct that is relevant. Both of them 
could then get fed into the C function as function pointers.

My concern is that `f` would then get called twice, whereas that 
wouldn't be the case in a simpler implementation (`gx_simple`, 
`gy_simple`). ldc will optimize the issue away in this simple 
example, but I worry that might not generally be the case.

How do I ensure that the commonCalculation is only done once?

```d
struct Foo
{
     int x;
     int y;
}

Foo f(int x, int a)
{
     int commonCalculation = a * x;
     return Foo(commonCalculation * x, 2 * commonCalculation);
}

int gx(int x, int a) { return f(x, a).x;}
int gy(int x, int a) { return f(x, a).y;}

//int gx_simple(int x, int a) { return a * x * x;}
//int gy_simple(int x, int a) { return 2 * a * x;}

void main() {
     import core.stdc.stdio: printf;
     printf("the value of x is %i\n", gx(3, 2));
     printf("the value of y is %i\n", gy(3, 2));
}
```


More information about the Digitalmars-d-learn mailing list