Click here to Skip to main content
15,914,014 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi

I have a enum

C++
typedef enum {
    one=1,
    two=2,
    three=3
}mynum;


and i have 4 different functions funtwo .. funfive as below

C++
void funtwo(mynum *c, uint8_t *num )
{
   int x= (int)num+c;
   printf( "num + c = %d \n", x);
}
void funthree(uint8_t *a , uint8_t *b, uint8_t *c )
{
    int x= (int)(*a+*b+*c);
     printf( "a+b+ c = %d \n", x);
}
void funfour(uint8_t *a , uint8_t *b, uint8_t *c, uint32_t *d )
{
   int x= (int)*a+(int)*b+(int)*c+(int)*d;
     printf( "a+b+c+d = %d \n", x);
}
void funfive(uint8_t *a , uint8_t *b, uint8_t *c, uint8_t *d, uint32_t *e)
{
    int x= (int)*a+(int)*b+(int)*c+(int)*d+(int)*e;
     printf( "a+b+c+d = %d \n", x);
}


now if my enum value is 1 then i have to use function 2
if enum is 2 then use fun 3,4 enum is 3 i have to use function 5

How do i do this without if else statement and using function pointers?

Thanks
Posted
Updated 29-Sep-15 0:56am
v2

There is no clever way for doing that, since function prototypes are not compatible (you might use a switch, instead of an if chain).

You could rearrange your functions, however, since they basically do the same thing on a different number of parameters, so, a single function like

int sum( int v[], int v_items);

could do the job.
 
Share this answer
 
Comments
Leo Chapiro 29-Sep-15 7:58am    
+5, nothing better to do!
CPallini 29-Sep-15 8:03am    
Thanks.
Do you mean something like this:

C
typedef void funtwoPtr(mynum *c, uint8_t *num);
typedef void funthreePtr(uint8_t *a , uint8_t *b, uint8_t *c );
/* 
...
...
the same for funfour and five */


funtwoPtr* myFunTwo = &funtwo;
funthreePtr* myFunThree = &funthree;
/* 
...
...
the same for funfour and five */

switch (eNum)
{
   case one:
   {
      myFunTwo(&eNum, &numOne);
      break;
   }
   case two:
   {
      myFunThree(&numOne, &numTwo, &numThree);
      break;
   }
   case three->whatever:
   {
      ...
   }
   default:
   {
      break;
   }
}

/*---------------------------------------------------------------*/
 
Share this answer
 
v4
Comments
CPallini 29-Sep-15 8:03am    
5.
Leo Chapiro 29-Sep-15 8:06am    
Many thanks !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900