Recursive declaration of function pointer in C

Recursive declaration of function pointer in C

坏尐絯 发布于 2021-11-25 字数 1258 浏览 816 回复 2 原文

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);
//...

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;
}

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

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁与争疯 2022-06-07 2 楼

This is discussed in Herb Sutter's book More Exceptional C++, Item 32, where the answer seems to be (for C) "not without use of casts". For C++ it is possible with the usual introduction of a class to provide some extra indirection.

猫九 2022-06-07 1 楼

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.