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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to use function pointer to call different functions in C

1 Answer

0 votes
#include <stdio.h>

void f1(void) {
    puts("f1");
}

void f2(void) {
    puts("f2");
}

void f3(void) {
    puts("f3");
}

void general(void) {
    puts("general");
}

void control(int x) {
    void (*p)(void);

    if (x == 1)
        p = f1;
    else if (x == 2)
            p = f2;
        else if (x == 3)
                p = f3;
            else
                p = general;
    p();
  }

int main(void)
{
    for (;;) {
        int x;

        printf("Enter a number (0 to exit): ");
        scanf("%d", &x);

        if (x == 0)
            break;

        control(x);
    }

    return 0;
}




/*
run:

Enter a number (0 to exit): 1
f1
Enter a number (0 to exit): 2
f2
Enter a number (0 to exit): 3
f3
Enter a number (0 to exit): 4
general
Enter a number (0 to exit): 15
general
Enter a number (0 to exit): 0

*/

 



answered May 8, 2023 by avibootz

Related questions

1 answer 108 views
2 answers 227 views
1 answer 109 views
1 answer 145 views
...