c - 功能类似于数组中的东西

标签 c anonymous-function

我如何才能以特定方式使用数组中的函数。现在,我把它设置成这样:

typedef void (*func_ptr)(void);
const func_ptr functions[] = {a, b};

inline void a(void)
{
    something = blah;
}

inline void b(void)
{
    anotherthing = blahblah;
}

我在想是否有办法缩短一点,也许是这样的:

const func_ptr functions[] = {(void)(something = blah;), (void)(anotherthing = blahblah;)};

内联函数 a 和 b 只包含一行代码,设置一些 #define

最佳答案

在 C 中你不能有匿名函数。

不过在 C++11 中,非捕获 lambda 会衰减为普通函数指针,因此您可以:

typedef void (*func_ptr)(void);
const func_ptr functions[] = {
    []() { something = blah; },
    []() { anotherthing = blahblah; }
};

关于c - 功能类似于数组中的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26020665/

相关文章:

c - 奇怪的代码行为?

c - 如何识别给定的单链表是否为循环?

php - 在 5.3 之前的 PHP 中使用 "create_function"比较器进行排序?

php - 带有匿名函数和闭包的 cURL WRITEFUNCTION 回调

function - 匿名函数 vs 非匿名函数 Lua

python - 无法从外部进程读取 PTY(伪终端文件)

c - 在 C 中使用 putchar 和 getchar 删除多个空格

将大端转换为小端的 C/C++ 代码

json - 在 JSON 结果中定义函数是否有效?

scala - 调用采用隐式方法返回的函数