如何避免在将函数指针作为参数的函数定义内提及函数指针的参数?

huangapple go评论72阅读模式
英文:

How to avoid mentioning a function pointer's arguments inside the definition of a function that takes it as argument?

问题

以下是翻译好的部分:

我正在编写这个涉及传递大量函数指针的C代码,有时在定义接受函数指针作为参数的函数时,写出函数指针所需的所有参数可以显著增加函数定义的长度,从而降低其可读性。例如,假设我有一个名为foo的函数,它接受三个int和一个函数指针来执行某个操作。声明类似于foo的函数的典型方式如下所示:

int foo(int a, int b, int c, int (*operation)(int, int, int));

我想知道是否有一种方法可以避免在函数指针的类型中再次提及变量类型的冗余。

这个问题的答案建议可以只使用空括号(),在上面的示例中翻译为:

int foo(int a, int b, int c, int (*operation)());

然而,对同一帖子的评论指出,这种语法将在C23中被移除:

顺便说一下,这是自1989年以来就已经过时的C语法。不应该使用空括号()的原型风格。它将在即将发布的C23中最终被移除。

英文:

I'm writing this C code that involves passing around a lot of function pointers, and sometimes writing all the arguments that a function pointer takes when defining a function that takes it as an argument can significantly increase the length of the function definition and thus decrease its readability. For instance, say I have this function foo that takes three ints and a function pointer to perform a certain operation. The typical way to declare a function like foo is something along the lines of:

int foo(int a, int b, int c, int (*operation) (int, int, int));

I was wondering if there was a way to avoid the redundancy of having to re-mention the variable types another time in the type of the function pointer.

An answer to this question suggests that it is possible to only use empty parentheses () , which translates in the above example to:

int foo(int a, int b, int c, int (*operation) ());

However, a comment to the same post states that this kind of syntax is going to be removed in C23:

> As a side note, this is obsolescent C since year 1989. Empty
> parenthesis () no prototype style should not be used. And it will
> finally get removed in upcoming C23

答案1

得分: 6

typedef int operation_t(int, int, int);
int foo(int a, int b, int c, operation_t *operation);

英文:

So, just make an alias. I like function aliases over function pointer aliases, so that I know it's a pointer.

typedef int operation_t(int, int, int);
int foo(int a, int b, int c, operation_t *operation);

huangapple
  • 本文由 发表于 2023年6月27日 16:56:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定