Ali Ashraf Dorgham
Ali Ashraf Dorgham

Reputation: 11

how to store pointer to function that takes arguments in Fsm?

I want to implement a function with arguments in FSM . when I try this, this error appears

error: initializer element is not constant
         {(&DriveCenter)(86),50,{stop,right,left,stop}},
 note: (near initialization for 'fsm[0].fun')
 error: initializer element is not constant
{(&DriveRight)(45),50,{stop,right,left,stop}},

Here is the code:

void DriveCenter(unsigned long out){
    printf("\ncenter = %d",out);
}

typedef struct  {
    void (*fun)(unsigned long out);
    unsigned long delay;
    unsigned long Next_State[4];
} state ;


state fsm[4] ={
        {(&DriveCenter)(86),50,{stop,right,left,stop}},
        {(&DriveRight)(45),50,{stop,right,left,stop}},
        {(&DriveLeft)(787),50,{stop,right,left,stop}},
        {(&DriveStop)(33),50,{stop,right,left,stop}}
};

Upvotes: 1

Views: 56

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You can not set a parameter when initializing a pointer to function, the parameter should be declared as another member of the struct

typedef struct  {
    void (*fun)(unsigned long);
    unsigned long out;
    unsigned long delay;
    unsigned long Next_State[4];
} state ;

state fsm[4] = {
    {DriveCenter,86,50,{stop,right,left,stop}},
    {DriveRight,45,50,{stop,right,left,stop}},
    {DriveLeft,787,50,{stop,right,left,stop}},
    {DriveStop,33,50,{stop,right,left,stop}}
};

Under C11 you can use anonymous structs to clarify that these two variables work together:

typedef struct  {
    struct {
        void (*fun)(unsigned long);
        unsigned long out;
    };
    unsigned long delay;
    unsigned long Next_State[4];
} state ;

state fsm[4] = {
    {{DriveCenter,86},50,{stop,right,left,stop}},
    {{DriveRight,45},50,{stop,right,left,stop}},
    {{DriveLeft,787},50,{stop,right,left,stop}},
    {{DriveStop,33},50,{stop,right,left,stop}}
};

Upvotes: 1

Related Questions