下面的代码有效,我觉得double(double)
和double(*)(double)
没有区别,square
和 &square
,我说得对吗?
#include <stdio.h>
double square(double x)
{
return x*x;
}
void test1(double f(double), double x)
{
printf("test1 %f\n", f(x));
}
void test2(double (*f)(double), double x)
{
printf("test2 %f\n", f(x));
}
int main()
{
double (*fp)(double);
test1(square, 3);
test2(square, 3);
fp = square;
test1(fp, 3);
test2(fp, 3);
fp = □
test1(fp, 3);
test2(fp, 3);
return 0;
}
但是下面的 cython 代码引发了 Cannot assign type 'double (*)(double)' to 'double (double)',这是一个错误还是我遗漏了什么?
from libc.stdio cimport printf
cdef double square(double x):
return x*x
cdef void test1(double f(double), double x):
printf("test1=%g\n", f(x))
cdef void test2(double (*f)(double), double x):
printf("test2=%g\n", f(x))
def test():
cdef double(*fp)(double)
fp = square
test1(fp, 3.0)
test2(fp, 3.0)
最佳答案
当您在函数参数列表中具体使用该表示法时,没有区别。
但在函数参数上下文之外,double(double)
是 function 类型,double (*)(double)
是 函数指针类型。这是两种具有截然不同属性的不同类型。
因此,您第一段的答案是:它在函数参数列表中为真,并且仅在函数参数列表中为真。
换句话说,当用于函数参数列表时,函数类型的行为方式与数组类型非常相似:它立即退化为指针类型。然而,正如数组和指针类型有很大不同一样,函数类型和函数指针类型也有很大不同。
在其他情况下,如果您声明类型为 double(double)
的内容,您将其声明为函数。例如
typedef double D(double);
D foo;
double foo(double);
以上两个声明有效且等价。它们声明函数 foo
,该函数接受类型为 double
的单个参数并返回 double
。此功能(通过 typedef
名称声明函数)通常不会在实际的 C 代码中使用,但它在语言中是存在的。
关于c - `double(double)` 和 `double (*)(double)` 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345109/