Re: An array of function pointers - generated parametrically
"John Doe" <john@doe.com> wrote in message news:fttucn$13h$1@news.onet.pl...
> Hello again and sorry for the different nicknames. I'm still
> struggling with my reader.
>
> On 2008-04-13, Walter Roberson <roberson@ibd.nrc-cnrc.gc.ca> wrote:
>>
>> There is no way to generate functions at run-time in C. There is
>> also no way to create an "instance" of a function that has some
>> stored value that is different than a different "instance" of the
>> same function. Or to phrase it in terms that some other languages
>> use, there are no "closures" in standard C.
>>
>
> That's a pity, but really: not a tragedy. There was an easy workaround
> in this case.
>
> On 2008-04-13, Bartc <bc@freeuk.com> wrote:
>>
>> Do you mean something like this?
>>
>> #include <stdio.h>
>>
>> float f0(float x){ return x*0;}
>> float f1(float x){ return x*1;}
>> float f2(float x){ return x*2;}
>>
>> float (*fntable[3])(float) = {&f0, &f1, &f2};
>>
>> int main(void)
>> {int i;
>> float x,y;
>>
>> for (i=0; i<3; ++i)
>> { x = i*10.0;
>> y = fntable[i](x);
>>
>> printf("%d : f%d(%f) = %f\n",i,i,x,y);
>> }
>>
>> }
>>
>
> No, what I meant was:
>
> 1. The value of n is determined at the runtime.
> 2. Space for an array of function pointers is allocated.
> 3. Now some magic is done and these pointers point to f_0, ... f_n.
>
> The point is, as I suppose, there is no way to dynamically allocate space
> for a function because its code size is unpredictable.
It's still not clear whether the code for these functions already exists
somewhere at compile-time.
Functions created at runtime aren't easy in C as has been pointed out.
But, although the code won't be as simple as you've indicated, could there
be any way of programmatically calculating what function n does? So for your
example, f_n(x) is simply x*n; you don't need an array of functions for
that.
So is there any similarity between functions that can be exploited? If you
give a few examples then we can see what's possible.
--
Bart
|