2017年12月23日 星期六

定義函數別名

base_example:
#include <stdio.h>
#include <stdlib.h>
int add(int a,int b){
    return (a+b);
}
int main()
{
    int n=add(7,2);
    printf("%d\n", n);
    system("pause");
}

相信上面這個例子,不需要我多做解釋,一看就明白,就是普通的"自訂函數",
如果,今天我兩個自訂函數,在main中定義一個函數別名func,為一個傳回值為integer且需要兩個integer parameters的函數,有以下作法可以使用:
example1:
#include <stdio.h>
#include <stdlib.h>
int add(int a,int b){
    return (a+b);
}
int division(int a,int b){
    return (a/b);
}
int main()
{
    typedef int (*func)(int a, int b);
    static volatile func f = add;  //宣告一個函數型態為func的函數別名f,並且套用add函數給f,也可以寫成"static volatile func f = (func)add;"

    int n=f(7,2);
    printf("add = %d\n", n);

    f=division;
    n=f(8,4);
    printf("division = %d\n", n);
    system("pause");
}


example2:
#include <stdio.h>
#include <stdlib.h>
int add(int a,int b){
    return (a+b);
}
int division(int a,int b){
    return(a/b);
}
int main()
{
    typedef int func(int a, int b);
    func *f = add;
    int n=f(7,2);
    printf("add = %d\n", n);

    f = division;
    n=f(8,4);
    printf("division = %d\n", n);
    system("pause");
}


example3:
#include <stdio.h>
#include <stdlib.h>
int func1(int a){
    a+=1;
    return (a);
}
int func2(int a){
    a+=3;
    return (a);
}
int main()
{
    typedef int (*func)(int a);
    static volatile func f = NULL;
    f=func1; //套用函數func1到f上,也可以寫成"f=(func)func1;"
    int x = f(1);
    printf("func1 = %d\n",x);

    f=func2;  //套用函數func2到f上,也可以寫成"f=(func)func2;"
    x = f(1);
    printf("func2 = %d\n",x);
    system("pause");
}

沒有留言:

張貼留言