从函数返回函数指针并用指针调用它。这是如何工作的?

时间:2020-10-05 21:32:49

标签: c function function-pointers function-call

因此,以下面的代码为例,我正在阅读一些有关函数指针的讲义,并且偶然发现了这一点:

int (*Convert(const char code))(int, int) {
    if (code == ‘+’) return ∑ // Takes two ints, and adds
    if (code == ‘-’) return &Difference; // Takes two ints, and subtracts
} 

int main () {
    int (*ptr)(int,int);
    ptr = Convert(‘+’);
    printf( “%d\n”, ptr(2,4));
} 

在调用返回函数指针的函数时,我通常会看到类似的东西,对我来说,这很有意义,因为我拥有此处列出的所有参数,char和这两个参数int

Convert('-')(5, 6);

但是按照注释中的方式,我无法真正掌握这里到底发生了什么。有人可以告诉我这是如何工作的吗?与分配(*ptr)(int, int)函数的地址或其他内容有关吗?

3 个答案:

答案 0 :(得分:2)

有人可以告诉我这是如何工作的吗?它与 分配(* ptr)(int,int)函数的地址还是什么?

函数Convert()返回指向函数的指针-指向Sum()的指针或指向Difference()的指针,具体取决于其参数(或者终止而未指定返回值,如果您对返回值做任何事情,这对您来说是个坏消息)。该函数指针存储在变量ptr中,该变量声明为与Convert()返回的类型相同。然后可以使用函数调用运算符()来调用指向的函数。

如果使用typedef以这种等效方式重写,也许会更加清楚:

typedef int (*op_function)(int, int);

op_function Convert(const char code) {
    if (code == ‘+’) return ∑ // Takes two ints, and adds
    if (code == ‘-’) return &Difference; // Takes two ints, and subtracts
} 

int main () {
    op_function ptr;
    ptr = Convert(‘+’);
    printf( “%d\n”, ptr(2,4));
}

答案 1 :(得分:0)

要么有错别字,要么是函数名AddSub而不是Convert

例如

int (*AddSub(const char code))(int, int) {
    if (code == ‘+’) return ∑ // Takes two ints, and adds
    if (code == ‘-’) return &Difference; // Takes two ints, and subtracts
}

[注意:请注意,由于例如函数指示符隐式转换为指向函数的指针,因此使用运算符&是多余的

int (*AddSub(const char code))(int, int) {
    if (code == ‘+’) return Sum; // Takes two ints, and adds
    if (code == ‘-’) return Difference; // Takes two ints, and subtracts
}

-尾注。]

因此调用类似的函数

AddSub('-');

您将获得指向类型int( int, int ).的函数的类型指针的表达式,并且可以再次向返回的指针提供参数,以像此类调用指向的函数

AddSub('-')(5, 6);

为了更清晰,您可以像上面那样重写表达式

( AddSub('-') )(5, 6);

与此代码段相同

int ( *ptr )( int, int ) = AddSub(‘+’);
printf( “%d\n”, ptr(2,4));

但没有中间变量ptr

printf( “%d\n”, AddSub( '+' )(2,4) );

答案 2 :(得分:0)

指向函数的指针始终引用该函数并可以被调用,但是它们的行为与其他指针完全相同。语法被许多人所混淆,这是将指针隐藏在typedef后面的地方之一,但这不是必须的

#include <stdio.h>
#include <stdlib.h>

typedef int func(int, int);

int Difference(int a, int b){
    return a - b;
}

int Sum(int a, int b){
    return a + b;
}

func *Convert(const char code) {
    if (code == '+') return Sum; // Takes two ints, and adds
    if (code == '-') return Difference; // Takes two ints, and subtracts
} 

int main () {
    func *ptr;
    ptr = Convert('+');
    printf( "%d\n", ptr(2,4));
} 

相关问题