问题
I am using an array of function pointers as below to avoid a switch
statement in the code.
void E_func1(void);
void E_func2(void);
void E_func3(void);
void (*pfGetVal[3])() = {
E_func1,
E_func2,
E_func3
};
But while running misra (pclint), I am getting the error below:
conversion between a pointer to function and another type [MISRA 2012 Rule 11.1, required]
Do I need to use typedef
?
I tried as below but didn't work.
void (*pfGetVal[3])();
pfGetVal[0] = E_func1;
pfGetVal[1] = E_func2;
pfGetVal[2] = E_func3;
回答1:
An empty parameter list void func ()
does not mean a function taking no parameters, but a function accepting any parameters. In C, the ()
form is obsolete style and should never be used.
Not to be confused with C++ where void func ()
and void func (void)
are identical.
Some compilers allow implicit conversions from ()
to (void)
style function pointers, but they are strictly speaking different types and MISRA-C checkers are much more pedantic than mainstream compilers when it comes to type safety.
Fix this by declaring the function pointer list as void (*pfGetVal[3])(void)
. Or better yet:
typedef void GetVal (void);
GetVal* const pfGetVal[3] =
{
E_func1,
E_func2,
E_func3
};
回答2:
The proper definition for pfGetVal
is:
void (*pfGetVal[3])(void) = {
E_func1,
E_func2,
E_func3
};
Unless you intend to modify this array during the execution of the program, you should define it as constant data:
void (* const pfGetVal[3])(void) = {
E_func1,
E_func2,
E_func3
};
来源:https://stackoverflow.com/questions/65596207/conversion-between-a-pointer-to-function-and-another-type-misra-2012-rule-11-1