函数指针用法

时间:2010-06-14 15:16:27

标签: c++ function-pointers

  

可能重复:
  How does dereferencing of a function pointer happen?

大家好, 为什么这两个代码给出相同的输出, 案例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));
}

输出:

the value is 7
the value is 3
the value is 10

案例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));
}

输出:

the value is 7
the value is 3
the value is 10

3 个答案:

答案 0 :(得分:5)

我会简化您的问题,以显示我认为您想知道的内容。

鉴于

typedef void (*mycall)(int a, int b);
mycall f = somefunc;

你想知道为什么

(*f)(5, 2);

f(5.2);

做同样的事情。答案是函数名称都代表“函数指示符”。从标准:

"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’’."

在函数指针上使用间接运算符*时,该取消引用也是“函数指示符”。从标准:

"The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;..."

因此,第一条规则f(5,2)基本上成为(*f)(5,2)。这成为第二个call to function designated by f with parms (5,2)。结果是f(5,2)(*f)(5,2)执行相同的操作。

答案 1 :(得分:3)

因为无论是否使用取消引用运算符,都会自动解析函数指针。

答案 2 :(得分:2)

你不必使用&amp;在函数名称之前

x[0] = addme;
x[1] = subme;
x[2] = mulme;

但两种方式都有效。