在C函数指针的递归声明 [英] Recursive declaration of function pointer in C

查看:110
本文介绍了在C函数指针的递归声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明指针返回到相同类型的功能的功能。

I'd like to declare a function that returns a pointer to a function of the same type.

我想用它来实现状态机像下面这样:

I would like to use it to implement state machines like the one below:

typedef event_handler_t (*event_handler_t)(event_t*); // compilation error

event_handler_t state2(event_t* e);
event_handler_t state1(event_t* e) {
	switch(e->type) {
	//...
	case SOME_EVENT:
		return state2;
	//...
	}

}
event_handler_t state2(event_t* e) {
	switch(e->type) {
	//...
	case OTHER_EVENT:
		return state1;
	//...
	}	
}

//...
event_handler_t event_handler;
//...
event_handler(&e);
//...

我设法解决使用结构compliation错误如下:

I manage to work around the compliation error using structures as follows:

typedef struct event_handler {
	struct event_handler (*func)(event_t *);
} event_handler_t;

不过,这使得回报率说明书更复杂的:

But this makes return statment more complicated:

event_handler_t state2(event_t* e) {
{
	event_handler_t next_handler = {NULL};
	switch(e->type) {
	//...
	case OTHER_EVENT:
		next_handler.func = state1;
		break;
	//...
	} 
	return next_handler;
}

我不知道是否有更好的方法在C来创建这样的函数指针。

I wonder if there is a better way to create such function pointers in c.

推荐答案

这是不可能做到这一点在C:一个指针的函数不能返回到自身,因为类型声明递归扩展和永远不会结束。有关详细说明,请参见本页面: http://www.gotw.ca/gotw/057.htm

It's not possible to do this in C: a function can't return a pointer to itself, since the type declaration expands recursively and never ends. See this page for an explanation: http://www.gotw.ca/gotw/057.htm

在上述网页介绍的替代方法是指返回无效(*)()而不是正确类型的函数指针;你的解决方法可以说是一个小整洁。

The workaround described on the above page means returning void (*) () instead of the correctly-typed function pointer; your workaround is arguably a little neater.

这篇关于在C函数指针的递归声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆