C: What even is function pointer conversion? [closed]

自古美人都是妖i 提交于 2019-12-06 20:29:30

It means that if you have two different function pointer types, such as for example:

int (*i)(int);
void (*v)(void);

Then you can make a conversion from one type to the other by using an explicit cast:

v = (void(*)(void))i;

This is allowed, but calling v() won't work. The standard says this, C17 6.3.2.3 §8:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

So if you try to call the function by v(); then it is likely undefined behavior. You can however convert back to the original type int(*)(int) without losing information.

This allows you to use a specific function pointer type as a "generic type". Rather than using void*, which isn't ok, as discussed here.


Notably, all code with function pointers get much easier to read if you use typedefs:

typedef int int_func (int);
typedef void void_func (void);

int main() 
{
  int_func*  i;
  void_func* v;

  v = (void_func*) i;

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