0

I have a set of functions:

int a1(int x, int, y)
{ do some stuff}

int a2(int x, int, y)
{ do some stuff}

//.........

int a100500(int x, int, y)
{ do some stuff}

Is there is a way to automatically initialize an array of pointers to function via FOR loop instead of explicitly typing a code like

int (*pfunc[100500])(int, int) = {a1, a2, ..., a1005000}

My first idea was to use #define directive in a following way:

#define z(n) a##n

// ..............

for (int i = 1; i< 100501;i++)
{ 
    pfunc[i] = z(i);
}

Unfortunately, z(i) becomes "ai" and not "a1", "a2", etc.

I hope, maybe some C-guru can help me with some advice.

16
  • boost has some macros to mock for loops in header; quite "ugly" but may help you if you really need it Commented May 23, 2019 at 14:45
  • 3
    OK, I gotta ask, why do you have 100k functions in the first place? Or rather, what’s your actual use-case? Commented May 23, 2019 at 14:45
  • 2
    @tenghiz That’s why I was asking (and am still interested in) actual use-cases. Commented May 23, 2019 at 14:49
  • 2
    10-15 entries can be populated "manually" with much less effort than using some esoteric tricks, which won't probably be much appreciated by your instructor. Commented May 23, 2019 at 15:00
  • 3
    This is almost certainly an "XY problem". You are most likely using the wrong solution to the original problem you are trying to solve. Commented May 23, 2019 at 15:08

1 Answer 1

2

Expanding @Giacomo Catenazzi's comment, consider the following (not great) python script:

# generate_funcs.py
import sys
with open('funcs.inc', 'w') as f:
    f.write(',\n'.join('a{}'.format(i + 1) for i in range(int(sys.argv[1]))))

Executed with the no. of your functions (python generate_funcs.py 100500), would produce a file called funcs.inc with:

a1,
a2,
...
a100500

You can then include it in your C code:

int (*pfunc[])(int, int) = {
#include "funcs.inc"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. Actually, I was sincerely persuaded that this is a trivial problem and I was just lacking a deeper knowledge of the language in order to implement my wish in a couple of lines of code. Your answer suggests that the solution must be different if I work on Windows platform. Heavens...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.