简体   繁体   English

C中嵌套回调function

[英]Nested callback function in C

I have written some code for calling nested functions using callback.我已经编写了一些使用回调调用嵌套函数的代码。 But i am not getting output as I expected.但我没有像预期的那样得到 output。

Please have look into code:请查看代码:

#include <stdio.h>
#include <stdlib.h>

typedef int (*f_ptr)(int a, int b);
typedef int (*pair_ptr)(f_ptr);

pair_ptr cons(int a, int b)
{

    int pair(f_ptr f)
    {
        return (f)(a, b);
    }
    return pair;
}

int car(pair_ptr fun)
{
    int f(int a, int b)
    {
        return a;
    }
    return fun(f);
}

int main()
{
    int a = 3;
    int b = 4;
    // It should print value of 'a'
    printf("%d", car(cons(a, b)));     // Error : It is printing '0'
    return 0;
}

I have also tried with function pointer but in that also i am getting the same output as above.我也尝试过使用 function 指针,但我也得到了与上面相同的 output。

Try this (maybe move functions and variables related to the closure to their own file):试试这个(也许将与闭包相关的函数和变量移动到它们自己的文件中):

#include <stdio.h>

typedef int (*f_ptr)(int a, int b);
typedef int (*pair_ptr)(f_ptr);

static int PairA, PairB;
static void setPairA(int a) { PairA = a; }
static void setPairB(int b) { PairB = b; }

int f(int a, int b) {
    (void)b; // removed unused parameter warning
    return a;
}

int pair(f_ptr fp) {
    return fp(PairA, PairB);
}

pair_ptr cons(int a, int b) {
    setPairA(a);
    setPairB(b);
    return pair;
}

int car(pair_ptr fun) {
    return fun(f);
}

int main(void) {
    int a = 3;
    int b = 4;
    printf("%d\n", car(cons(a, b)));
    return 0;
}

Note that pair() is not reentrant, nor can you call it with different values for PairA and/or PairB at the same time.请注意, pair()不可重入,您也不能同时为PairA和/或PairB使用不同的值来调用它。

C doesn't support nested function, but a GCC extension does. C 不支持嵌套 function,但 GCC 扩展支持。 The docs say:文档说:

If you try to call the nested function through its address after the containing function exits, all hell breaks loose.如果您尝试在包含 function 退出后通过其地址调用嵌套的 function,一切都会崩溃。

pair tries to use a and b which no longer exist. pair尝试使用不再存在ab GCC might provide nested functions, but they don't provide closures . GCC 可能提供嵌套函数,但不提供闭包 This means the values of a and b aren't captured by the function;这意味着ab的值没有被 function 捕获; it's merely an address being returned by cons .它只是cons返回的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM