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

Recommended Answers

All 5 Replies

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()
{
    printf("hello\n");
}


void somethingElse()
{
    printf("hello2\n");
}

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

   pointer();
   
   pointer = somethingElse;

   pointer();

    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
     pfct("Laiq");
     
     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.

Amazing Article :). Thanks from my side :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.