函數指針是一種CC++D語言、其他類C語言和Fortran2003中的指針。函數指針可以像一般函數一樣,用於調用函數、傳遞參數。在如C這樣的語言中,通過提供一個簡單的選取、執行函數的方法,函數指針可以簡化代碼。

函數指針只能指向具有特定特徵的函數。因而所有被同一指針運用的函數必須具有相同的參數個數和型態和返回類型。

C/C++編程語言 編輯

C語言標準規定,函數指示符(function designator,即函數名字)既不是左值,也不是右值。但C++語言標準規定函數指示符屬於左值,因此函數指示符轉換為函數指針的右值屬於左值轉換為右值。

除了作為sizeof或取地址&的操作數,函數指示符在表達式中自動轉換為函數指針類型右值。[1]因此通過一個函數指針調用所指的函數,不需要在函數指針前加取值或反參照(*)運算符。

實例 編輯

以下為函數指針在C/C++中的運用

/* 例一:函式指標直接呼叫 */

# ifndef __cplusplus
    # include <stdio.h>
# else
    # include <cstdio>
# endif

int max(int x, int y)
{
    return x > y ? x : y;
}

int main(void)
{
    /* p 是函式指標 */
    int (* p)(int, int) = & max; // &可以省略
    int a, b, c, d;

    printf("please input 3 numbers:");
    scanf("%d %d %d", & a, & b, & c);

    /* 與直接呼叫函式等價,d = max(max(a, b), c) */
    d = p(p(a, b), c); 

    printf("the maxumum number is: %d\n", d);

    return 0;
}


/* 例二:函式指標作為參數 */

struct object
{
    int data;
};

int object_compare(struct object * a,struct object * z)
{
    return a->data < z->data ? 1 : 0;
}

struct object *maximum(struct object * begin,struct object * end,int (* compare)(struct object *, struct object *))
{
    struct object * result = begin;
    while(begin != end)
    {
        if(compare(result, begin))
        {
            result = begin;
        }
        ++ begin;
    }
    return result;
}

int main(void)
{
    struct object data[8] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}};
    struct object * max;
    max = maximum(data + 0, data + 8, & object_compare);
    return 0;
}

腳註 編輯

  1. ^ C++語言標準規定: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’』.

相關條目 編輯