Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,698 questions

57,007 answers

573 users

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 222 views
2 answers 339 views
2 answers 364 views
1 answer 239 views
2 answers 309 views
...