How to use function pointer array to operate on different types of variables in C

1 Answer

0 votes
#include <stdio.h>

enum TYPE {INTEGER, LONG, DOUBLE, ERROR};

#define typename(x) _Generic((x), \
          int: INTEGER, \
          long: LONG, \
          double: DOUBLE, \
          default: ERROR)

typedef void (*FuncPtr)();

void printInt(int x) {
    printf("printInt: %d\n", x);
}

void printLong(long x) {
    printf("printLong: %ld\n", x);
}

void printDouble(double x) {
    printf("printDouble: %.3f\n", x);
}

int main() {
    int n = 872;
    long l = 940937471;
    double d = 37379.891;

    FuncPtr func_ptr[] = {printInt, printLong, printDouble};

    switch (typename(n)) {
        case INTEGER: func_ptr[INTEGER](n); break;
        case LONG: func_ptr[LONG](l); break;
        case DOUBLE: func_ptr[DOUBLE](n); break;
        case ERROR: printf("ERROR\n");
        default: break;
    }

    switch (typename(l)) {
        case INTEGER: func_ptr[INTEGER](n); break;
        case LONG: func_ptr[LONG](l); break;
        case DOUBLE: func_ptr[DOUBLE](n); break;
        case ERROR: printf("ERROR\n");
        default: break;
    }

    switch (typename(d)) {
        case INTEGER: func_ptr[INTEGER](d); break;
        case LONG: func_ptr[LONG](l); break;
        case DOUBLE: func_ptr[DOUBLE](d); break;
        case ERROR: printf("ERROR\n");
        default: break;
    }

    return 0;
}




/*
run:

printInt: 872
printLong: 940937471
printDouble: 37379.891

*/

 



answered May 7, 2021 by avibootz

Related questions

1 answer 131 views
2 answers 208 views
2 answers 214 views
1 answer 143 views
2 answers 183 views
...