'"expression must have a constant value" error while using function pointer

Am getting the error as specified in the title [ using c language]

There is a struct defined

typedef struct {
uint a;
mytype b;
} structName

where mytype is defined as

typedef void (*mytype) (void);

A const array of type structName is defined as:

CONST(structName, memclass) arr[] = {
{val1, NULLPTR},
{val2, &somefunc}, // somefunc has type 'mytype'
.
.
.
}; 

I have a function and respective function pointer say :

void func(int,int);
void (*ptr)(int, int) = &func;

Now I want to add this function pointer to the above array something like this:

{val3, (*ptr)(1,2)},

But I am getting error : expression must have a constant value

What changes to make in the ptr to make this work?



Solution 1:[1]

As mentioned in comments, you cannot use a function call in an initializer list.

Also the return type of your called function does not match the type of the second struct member.

Instead of calling the function you must provide a function pointer.

Normally that would look like this:

{val3, func},

In your specific case this will not work properly. The second member of your struct has type void(*)(void) while your function is void()(int, int). Whenever you use that pointer from the struct, no one will provide the extra arguments. In case your function uses these parameters, you will invoke undefined behaviour.

If you want to have your function called with parameters 1,2 you might create a wrapper function for that purpose:

void func_wrapper(void)
{
   func(1,2);
}

...
{val3, func_wrapper}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gerhardh