函式指標是一種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’』.

相關條目 編輯