Featured Post

Trie implementation in C

Function Pointers in C

Generally functions are called statically , i.e. it is already decided at compile time itself that which particular function would be called. But we can also make this decision at runtime by the use of what is called 'function pointers'.

This is a simple implementation showing how to use function pointers in C.
#include <stdio.h>
#include <stdlib.h>

void func1()
{
  printf("I am in Function 1\n");
}

void func2()
{
  printf("I am in Function 2\n");
}

void func3()
{
  printf("I am in Function 3\n");
}

int main()
{
  int choice;

  void (*fptr)(void);

  printf("\nEnter a choice: ");
  scanf("%d",&choice);
 
  switch(choice)
  {
    case 1:
      fptr = func1;
      break;
    case 2:
      fptr = func2;
      break;
    case 3:
      fptr = func3;
      break;
    default:
      printf("Choose from 1-3!");
      break;
  }

  fptr();
}

Comments