LoginSignup
5
3

More than 5 years have passed since last update.

c言語_関数ポインタの配列を使う

Last updated at Posted at 2017-04-26
main.c

#include <stdio.h>

typedef int (*fptrOperate)(int, int);
fptrOperate operations[128] = {NULL}; // int (*operations[128])(int, int) = {NULL}


int add( int num1, int num2 ){
    return num1 + num2;
}


int sub( int num1, int num2 ){
    return num1 - num2;
}


int multi( int num1, int num2 ){
    return num1 * num2;
}


int unko( int num1, int num2 ){
    return 777; // unko
}


void initialize(){
    operations['+'] = add;
    operations['-'] = sub;
    operations['*'] = multi;
    operations['u'] = unko;
}

int evaluate(char opcode, int num1, int num2){
    fptrOperate operate;
    operate = operations[opcode];
    return operate(num1, num2);
}


int main(int argc, const char * argv[]) {
    initialize();
    printf("evaluate('+',10,100)=%d\n", evaluate('+', 10, 100));
    printf("evaluate('-',10,100)=%d\n", evaluate('-', 10, 100));
    printf("evaluate('*',10,100)=%d\n", evaluate('*', 10, 100));
    printf("evaluate('u',10,100)=%d\n", evaluate('u', 10, 100));
    return 0;
}


関数のポインタの配列(=operations)を使って、
関数(=evaluate)の機能を切り替えられるようにしてみたという、サンプルコードです。

./main.o

evaluate('+',10,100)=110
evaluate('-',10,100)=-90
evaluate('*',10,100)=1000
evaluate('u',10,100)=777

参考:

詳説Cポインタ

  
  
どやっ!

5
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3