英文:
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 int
s 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论