C函数指针 [英] C function pointers
问题描述
静态无效增量(很久很久* N){
(* N)++;
}结构试验{
无效(* work_fn)(长*长);
};结构测试T1;t1.work_fn =增量;
我怎么现在实际上调用该函数? t1.work_fn(安培; N)?
我怎么现在实际上调用该函数?
t1.work_fn?(安培; N)
块引用>这会工作得很好。
函数指针并不需要明确取消引用。这是因为通常调用函数,即使(使用功能的实际名称),你真的通过函数指针调用它。 C99 6.5.22函数调用说:(重点煤矿):
这表示调用的函数(脚注77)应具有指针类型的前pression运作返回void或返回比数组类型以外的对象类型
块引用>77脚注:
大多数情况下,这是转换的标识符是一个功能指示符的结果。
块引用>请注意,您仍然可以的间接引用函数指针(或正常功能的名字 - 虽然我认为你会造成很大的混乱这样做)来调用一个函数,因为C99 6.5.3.2/4地址和间接运算符说:
单目*运算符表示间接。如果操作数指向一个函数,其结果是一个功能指示符
块引用>因此,所有这些最终会做同样的事情(尽管编译器可能无法优化来电通
t1.work_fn
以及):t1.work_fn(安培; N);
(* t1.work_fn)(安培; N);增量(安培; N);
(*增量)(安培; N);static void increment(long long *n){ (*n)++; } struct test{ void (*work_fn)(long long *); }; struct test t1; t1.work_fn = increment;
How do I actually call the function now? t1.work_fn(&n) ?
解决方案How do I actually call the function now?
t1.work_fn(&n)
?That'll work just fine.
Function pointers don't need to be explicitly dereferenced. This is because even when calling a function normally (using the actual name of the function), you're really calling it through the pointer to the function. C99 6.5.22 "Function calls" says (emphasis mine):
The expression that denotes the called function (footnote 77) shall have type pointer to function returning void or returning an object type other than an array type
Footnote 77:
Most often, this is the result of converting an identifier that is a function designator.
Note that you still can dereference the function pointer (or a normal function name - though I think you'd cause much confusion doing so) to call a function because C99 6.5.3.2/4 "Address and indirection operators" says:
The unary * operator denotes indirection. If the operand points to a function, the result is a function designator
So all of these will end up doing the same thing (though the compiler might not be able to optimize the calls-through
t1.work_fn
as well):t1.work_fn(&n); (*t1.work_fn)(&n); increment(&n); (*increment)(&n);
这篇关于C函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!