如何在C中将简单的匿名函数作为参数传递

RLH*_*RLH 5 c

我确信之前已经提出了这个问题的一些变体,但所有其他类似的关于SO的问题似乎要复杂得多,涉及传递数组和其他形式的数据.我的场景更简单,所以我希望有一个简单/优雅的解决方案.

有没有办法可以创建一个匿名函数,或者将一行代码作为函数指针传递给另一个函数?

就我而言,我有一系列不同的操作.在每行代码之前和之后,我想要完成的任务永远不会改变.我想编写一个函数,它将函数指针作为参数并以必要的顺序执行所有代码,而不是复制开始代码和结束代码.

我的问题是,为每个操作定义30个函数是不值得的,因为它们都是一行代码.如果我无法创建匿名函数,有没有办法可以简化我的C代码?

如果我的要求不完全清楚.这里有一些伪代码用于澄清.我的代码比这更有意义,但下面的代码得到了相应的点.

void Tests()
{
  //Step #1
  printf("This is the beginning, always constant.");
  something_unique = a_var * 42;  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;

  //Step #2
  printf("This is the beginning, always constant.");
  a_diff_var = "arbitrary";  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;

  ...
  ...

  //Step #30
  printf("This is the beginning, always constant.");
  var_30 = "Yup, still executing the same code around a different operation.  Would be nice to refactor...";  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;
}
Run Code Online (Sandbox Code Playgroud)

Foo*_*Bah 9

不是传统意义上的匿名函数,但你可以将它宏:

#define do_something(blah) {\
    printf("This is the beginning, always constant.");\
    blah;\
    printf("End code, never changes");\
    a_var++;\
}
Run Code Online (Sandbox Code Playgroud)

然后它变成了

do_something(something_unique = a_var * 42)
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但内部允许的声明有限制; 例如,它不能包含任何逗号.您可以将其拆分为两个没有参数的宏,一个在变量语句之前,一个在之后. (3认同)