[英]C callbacks through the function pointer and without it. Why there is no difference?
I cannot understand why different code works as it will be identical. 我不明白为什么不同的代码可以正常工作。
#include <stdio.h>
void foo() {
printf("Hello\n");
}
void foo1(void fn()) {
(*fn)();
fn();
}
void foo2(void (*fn)()) {
(*fn)();
fn();
}
int main(void) {
foo1(foo);
foo2(foo);
return 0;
}
If they identical then why this does not work? 如果它们相同,那为什么不起作用?
typedef void F1(), (*F2)();
int main(void) {
F1 f1;
F2 f2;
// error: lvalue required as left operand of assignment
f1 = foo1;
f2 = foo2;
return 0;
}
PS 聚苯乙烯
My interest are not in the typedef
(second example). 我感兴趣的不是typedef
(第二个示例)。
I have questions only about the first example. 我仅对第一个示例有疑问。
That is: 那是:
You are using the typedef incorrectly. 您使用的typedef错误。 The first F1()
is not a function pointer at all. 第一个F1()
根本不是函数指针。 Your second part does correctly provide a typedef for a function pointer (*F2)()
, but you fail to include a type. 您的第二部分确实为函数指针(*F2)()
提供了typedef,但是您没有包含类型。 Bottom line, but you don't get 2 function pointer typedefs in one line: 底线,但您不会在一行中得到2个函数指针typedef:
typedef void (*F1)();
typedef void (*F2)();
Will create both a typedef for F1
and a typedef for F2
. 将创建既为一个typedef F1
和一个typedef F2
。
As far as the use of the function pointers, the function pointers may be used with, or without, parens and the dereference. 就功能指针的使用而言 ,可以在有或没有parens和取消引用的情况下使用功能指针。
(*fn)();
fn();
Both are equivalent and simply call the function pointed to by fn
. 两者都是等效的,只需调用fn
指向的函数。
The lines 线
typedef void F1();
F1 f1;
do not declare f1
as a pointer. 不要将f1
声明为指针。 They declare f1
as a function returning void
. 他们将f1
声明为返回void
的函数。 The equivalent declaration is 等效的声明是
void f1();
This can be demonstrated by the following code, which will compile without any errors or warnings. 下面的代码可以证明这一点,它将在编译时没有任何错误或警告。 Note that if you comment out the line F1 f1;
请注意,如果您注释掉F1 f1;
行F1 f1;
, then the compiler will complain about "implicit declaration of function f1" and "conflicting types for f1" because you have a forward reference without a declaration. ,那么编译器会抱怨“函数f1的隐式声明”和“ f1的类型冲突”,因为您有一个没有声明的前向引用。
typedef void F1();
int main(void)
{
F1 f1;
f1();
return 0;
}
void f1()
{
printf( "hello\n" );
}
On the other hand, the following code will also compile without warning or error, but in this case the compiler treats f1
like a pointer to a function. 另一方面,下面的代码也将在没有警告或错误的情况下进行编译,但是在这种情况下,编译器将f1
视为指向函数的指针。
typedef void F1();
void foo() {
printf( "hello\n" );
}
void foo1(F1 f1) {
f1();
}
int main(void) {
foo1( foo );
return 0;
}
Why the difference? 为什么会有所不同? Because §6.7.6.3 Function declarators, paragraph 8 reads 因为§6.7.6.3函数声明符,第8段为
A declaration of a parameter as "function returning type" shall be adjusted to "pointer to function returning type", as in 6.3.2.1. 如6.3.2.1中所述,将参数声明为“函数返回类型”声明调整为“指向函数返回类型的指针”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.