Passing a pointer to a function as an argument. - C Function

C examples for Function:Function Parameter

Description

Passing a pointer to a function as an argument.

Demo Code

#include <stdio.h>

void func1(void (*p)(void));
void one(void);
void two(void);
void other(void);

int main( void ){
    void (*ptr)(void);
    int nbr;/*from  w  ww .  j a  v a  2  s  .co m*/

    for (;;){
        puts("\nEnter an integer between 1 and 10, 0 to exit: ");
        scanf("%d", &nbr);

        if (nbr == 0)
            break;
        else if (nbr == 1)
            ptr = one;
        else if (nbr == 2)
            ptr = two;
        else
            ptr = other;
        func1(ptr);
    }
    return 0;
}

void func1(void (*p)(void))
{
    p();
}

void one(void)
{
    puts("1.");
}

void two(void)
{
    puts("2.");
}

void other(void)
{
    puts("other than 1 or 2.");
}

Related Tutorials