相关疑难解决方法(0)

有没有办法在C中实现闭包

我希望这可以工作,但它没有:

#include <stdio.h>

typedef struct closure_s {
  void (*incrementer) ();
  void (*emitter) ();
} closure;

closure emit(int in) {

  void incrementer() {
    in++;
  }

  void emitter() {
    printf("%d\n", in);
  }

  return (closure) {
    incrementer,
    emitter
  };
}

main() {
  closure test[] = {
    emit(10),
    emit(20)
  };

  test[0] . incrementer();
  test[1] . incrementer();

  test[0] . emitter();
  test[1] . emitter();
}
Run Code Online (Sandbox Code Playgroud)

它实际上编译和1个实例不工作...但第二个失败.知道如何在C中获得闭包吗?

真的很棒!

c closures

32
推荐指数
5
解决办法
2万
查看次数

在函数实现中如何使用函数的函数参数?

如果我有这样的声明:

int foo1 (int foo2 (int a));
Run Code Online (Sandbox Code Playgroud)

如何实现此foo1功能?喜欢,

int foo1 (int foo2 (int a))
{
    // How can I use foo2 here, which is the argument?
}
Run Code Online (Sandbox Code Playgroud)

我该如何调用foo1函数main?喜欢:

foo1(/* ??? */);
Run Code Online (Sandbox Code Playgroud)

c function-pointers

3
推荐指数
1
解决办法
61
查看次数

在 C++ 中将数组传递给函数的不同语法

#include <stdio.h>

void test2(int (&some_array)[3]){
  // passing a specific sized array by reference? with 3 pointers?
}

void test3(int (*some_array)[3]){
  // is this passing an array of pointers?
}

void test1(int (some_array)[3]){
  // I guess this is the same as `void test1(some_array){}`, 3 is pointless.
}

int main(){
  //
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

以上3种语法有什么区别?我在每个部分都添加了评论,以使我的问题更加具体。

c++

2
推荐指数
1
解决办法
66
查看次数

标签 统计

c ×2

c++ ×1

closures ×1

function-pointers ×1