conversion between a pointer to function and another type [MISRA 2012 Rule 11.1, required] | pclint 9074

走远了吗. 提交于 2021-01-27 19:20:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!