函数指针用法

cha*_*rma 3 c++ function-pointers

可能重复:
如何解除引用函数指针?

大家好,为什么这两个代码给出相同的输出,案例1:

#include <stdio.h>

typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);

main()
{
    mycall x[10];
    x[0] = &addme;
    x[1] = &subme;
    x[2] = &mulme;
    (x[0])(5,2);
    (x[1])(5,2);
    (x[2])(5,2);
}

void addme(int a, int b) {
    printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
    printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
    printf("the value is %d\n",(a-b));
}
Run Code Online (Sandbox Code Playgroud)

输出:

the value is 7
the value is 3
the value is 10
Run Code Online (Sandbox Code Playgroud)

案例2:

#include <stdio.h>

typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);

main()
{
    mycall x[10];
    x[0] = &addme;
    x[1] = &subme;
    x[2] = &mulme;
    (*x[0])(5,2);
    (*x[1])(5,2);
    (*x[2])(5,2);
}

void addme(int a, int b) {
    printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
    printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
    printf("the value is %d\n",(a-b));
}
Run Code Online (Sandbox Code Playgroud)

输出:

the value is 7
the value is 3
the value is 10
Run Code Online (Sandbox Code Playgroud)

Tim*_*fer 5

我会简化你的问题,以显示我想你想知道什么.

特定

typedef void (*mycall)(int a, int b);
mycall f = somefunc;
Run Code Online (Sandbox Code Playgroud)

你想知道为什么

(*f)(5, 2);
Run Code Online (Sandbox Code Playgroud)

f(5.2);
Run Code Online (Sandbox Code Playgroud)

做同样的事.答案是函数名称都代表"函数指示符".从标准:

"A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator or the unary & operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’."
Run Code Online (Sandbox Code Playgroud)

*函数指针上使用间接运算符时,该解除引用也是"函数指示符".从标准:

"The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;..."
Run Code Online (Sandbox Code Playgroud)

所以f(5,2)基本上(*f)(5,2)成为第一条规则.这成为call to function designated by f with parms (5,2)第二个.结果是,f(5,2)(*f)(5,2)做同样的事情.

  • 认为你有一个小错字,*mycall ---> myfunc (2认同)