c - `double(double)` 和 `double (*)(double)` 有什么区别

标签 c function-pointers cython

下面的代码有效,我觉得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 = &square;
    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/

相关文章:

c++ - 如何使用需要指向 C++ 中 void 函数的指针的 Functor 来调用 C 函数?

cython - 在 Cython 中将结构自动转换为字典

在函数中更改指针地址

二维数组的 C 指针

c - Pthreads:我的并行代码在达到一定数量后不会将线程传递到函数中

c - 修复 "undefined reference to"ft. makefile.txt 和 pthreads

c - 什么是函数指针

c - 在c中使用typedef关键字

c++ - 如何在 Cython 中定义返回 cpp 定义类型的函数?

c++ - Cython:共享对象中 undefined symbol