10 Years
Discussion Span
Last Post by Laiq Ahmed

can anyone tell me what are pointers to function ??? and how are they implemented ??

in C, functions are defined just like variable.

The adress of a function can be assimiled to its adress in memory, so the following code is valid :

#include <stdio.h>

void something()

void somethingElse()

int main(void)
   (void)(*pointer)() = something;

   pointer = somethingElse;


    return 0;

Pointer to function are the pointers which have the ability to call the function pointed to by them.As the ordinary pointers take the address of variable and can change the value pointed by them, the function pointer almost does the same.

#include <iostream>
#include <string>
using std::string;
using std::cout;
//simple function
void print(string _name) { std::cout<<"Hello"<<_name; }
//another function with return type int.
int cal_pay(double _pay,int _hours) 
    return (2*_pay + 1000)*_hours;
//function pointer of the same type i.e. complete function type must match exactly
void (*pfct)(string);   //check the return type and arguments   
int (*cfct)(double,int);
int main() 
     pfct=&print;             //pfct points to print function
     cfct=cal_pay            //also o.k. same as &cal_pay
     int ans = (*cfct)(500.00,4);    //another way of calling 
     return 0;

you can use typedef to clean declaration
typedef void (*pfct)(string);
void say(string);
void no(string);
void yes(string);
pfct my[] = { &say, &no, &yes };

also you can use the pointer to function in function's argument to specifify the details... like comparision criteria in sort funciton ;

typedef int (*Comfct)(MyType const*, MyType const*);
void sort(vector<MyType>& v,size_t n, Comfct Cmp);

Hope you got the basic idea..............


Mainly used in TSR programming in old days , where old IVT vector function 's address is stored as a pointer to a function.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.