By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,985 Members | 1,885 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,985 IT Pros & Developers. It's quick & easy.

how to use enum with array of function pointers ?

P: 1
Hello all,

I want to initialize the pointers to functions, which i have declared in an array.
e.g

#include <math.h>
typedef double (*Fx)(double x); // pointer to function

int main(void)
{
Fx f[3]; //array of function pointers

f[0] = cos;
f[1] = sin;
f[2] = tan;
.
.
.
.
.
}
This approach is ok if the number of functions is small.

If I have ,say 200 functions and I want to use pointer to function, how can i initialize so many pointers?
I was thinking about using enum for storing name of functions, but cannot implement exactly as i doubt whether if i use enum instance instead of function name, will it work?

Plz do suggest me...
Aug 13 '07 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
If you have 200 functions you don't need 200 function pointers unless every function has different arguiments ro return types.

The idea of the function pointer is to decide at run time what function to call based on runtime coinditions.

An enum is just a named integer value. Enums are used to avoid harde-coding integers in your program.

You could use an enum to help you decide what function to call.

Assume you have two functions:
Expand|Select|Wrap|Line Numbers
  1. int MyFunction(int, int);
  2. int YourFunction(int, int);
  3. //and a function pointer:
  4.  
  5. int (*fp)(int, int);
  6.  
  7.  
You could do this:

Expand|Select|Wrap|Line Numbers
  1. enum funcs {MYFUNCTION, YOURFUNCTION};
  2. .....
  3.  
  4. switch (funcs)
  5. {
  6.     case MYFUNCTION:
  7.             fp = MyFunction;
  8.             break;
  9.     case YOURFUNCTION:
  10.             fp = YourFunction;
  11.             break;
  12. ....
  13. }
  14.  
Aug 13 '07 #2

RRick
Expert 100+
P: 463
You can also use enums to designate the position of the function within the array.

Expand|Select|Wrap|Line Numbers
  1. enum  { Sin=0, Cos, ... };
  2. ........
  3. // Initialization
  4. fx[ Sin] = ::sin;
  5. fx[ Cos] = ::cos;
  6. ........
  7. double sinValue = fx[Sin]( .8999);  //  Assuming radians are used
  8.  
Now you control how the pointers are used.

One other point, only the functions that exactly match the Fx typedef will compile with C++. If you have a function that takes 2 parameters, then the compiler will complain.
Aug 14 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.