Page 1 of 1

## Basics Of Function Pointers What are function pointers and how to use them Rate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=23759&amp;s=5c1fc49f4a7289ddf9681d201cdd542b&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

Posted 09 February 2007 - 03:57 AM

This is my first tutorial. Though I tried my best, please forgive me for spelling and grammer mistakes.
And don't forget to comment and rate me so I will perform better next time.

If you can't get it properly from post then you can download the document attached.

Function Pointers

Introduction
Function Pointers provide some extremely interesting, efficient and elegant programming
techniques. We can use them to replace switch/if statements, to realize our own late-binding or to
implement callbacks. Unfortunately probably due to their complicated syntax they are treated quite step
motherly in most computer books and documentations. If at all, they are addressed quite briefly. They
are less error prone than normal pointers cause we will never allocate or de-allocate memory with them.
All we’ve got to do is to understand what they are and to learn their syntax. But keep in mind:
It’s important to check whether we really need a function pointer. It’s nice to realize one’s own late-binding
but to use the existing structures of C++ may make our code more readable and clear.

What Is a Function Pointer ?
Function Pointers are pointers, i.e. variables, which point to the address of a function. We must
keep in mind, that a running program gets a certain space in the main-memory. Both, the executable
compiled program code and the used variables, are put inside this memory. Thus a function in the program
code is, like e.g. a character field, nothing else than an address. It is only important how we, or better our
compiler/processor, interpret the memory a pointer points to.

How To Define a Function Pointer ?
Since a function pointer is nothing else than a variable, it must be defined as usual.
Let’s take an example, we will define function pointers ptrToFunc, ptrToMember and
ptrToConstMember. The first is for C and will point to function which takes float and char as parameters and
returns integer.
Other Two are for C++ and will point to functions which takes float and char as parameters
and returns integer and are non-static members of class MyClass.
```int (*ptrToFunc)(float, char) = NULL; // in C
int (MyClass::*ptrToMember)(float, char) = NULL; // C++
int (MyClass::*ptrToConstMember)(float, char) const = NULL; // C++

```

So in general we can say it is something like :

<return datatype of function> (* <pointer name>) (<parameters of function>);

[ It is a good practice to initialize function pointers with NULL. ]

How To Assign An Address to A Function Pointer ?
It’s quite easy to assign the address of a function to a function pointer. Simply take the name of a
suitable and known function or member function. Although it’s optional for most compilers we should use the
address operator “&” in front of the function’s name in order to write portable code. We may have got to use
the complete name of the member function including class-name and scope-operator "::" [For C++]. Also we
have got to ensure, that we are allowed to access the function right in scope where our assignment stands.
```// C
int SendIt (float a, char b)
{ printf("SendIt %f\n",a); return atoi(b); }

int SendIt2(float a, char b) const
{ printf("SendIt2 %f\n",a); return atoi(b); }

ptrToFunc = SendIt; // short form
ptrToFunc = &SendIt; // correct assignment using address operator

// C++
class MyClass
{
public:
int SendIt (float a, char b)
{ cout << "MyClass::SendIt "<<a<<endl; return atoi(b); }

int SendIt2(float a, char b)const
{ cout << "MyClass::SendIt2”<<a<<endl; return atoi(b); }

/* more code will follow*/
};

ptrToConstMember = &MyClass::SendIt2; // correct assignment using address
//operator
ptrToMember = &MyClass::SendIt;
// ptrToMember can also legally point to &MyClass::SendIt2

```

How To Call a Function using a Function Pointer ?
In C we call a function using a function pointer by explicitly dereferencing it using the * operator.
Alternatively we may also just use the function pointers instead of the function name. In C++ the two operators “.*”
and “->*” are used together with an instance of a class in order to call one of their (non-static) member functions. If
the call takes place within another member function we may use the “this” pointer.
```int result1 = ptrToFunc(12, ’a’); // C short way
int result2 = (*ptrToFunc) (12, ’a’); // C

MyClass instance1= new MyClass;
int result3 = (instance1.*ptrToMember)(12, ’a’); // C++
//call from inside member function
int result4 = (*this.*ptrToMember)(12, ’a’); // C++ if this-pointer can be used
MyClass* instance2 = new MyClass;
int result4 = (instance2->*ptrToMember)(12, ’a’); // C++, instance2 is a pointer

```

How To Compare Function Pointers ?
We can use the comparison-operators (==, !=) the same way as usual.
Following is the example of it.
```// C
if(ptrToFunc >0) // check if initialized
if(ptrToFunc == &SendIt) //compare to check whether is points to SendIt

// C++
if(ptrToConstMember >0)
if(ptrToConstMember == &MyClass::SendIt2)

```

How to Pass a Function Pointer as an Argument ?
We can pass a function pointer as a function’s calling argument. We need this many times
e.g. while passing a pointer to a callback function.
```void PassPtr(int (*ptrToFunc)(float, char))
// This contains one parameter int (*ptrToFunc)(float,char) you can
// understand now what it is…
{
int result = (*ptrToFunc)(12, ’a’); // call using function pointer
cout << result << endl;
}
// execute code - ’SendIt’ is a suitable function as defined in above codes
void Pass_A_Function_Pointer()
{
PassPtr(&SendIt);
}

```

How to Return a Function Pointer ?
It’s a little bit tricky but a function pointer can be a function’s return value. Here I am giving
two ways of how to return a pointer to a function which is taking two float arguments and returns a float.
If you want to return a pointer to a member function you have just got to change the definitions/declarations
of all function pointers.
```// specifies which function to return
float (*GetPtr1(int a, int b))(float, float)
//here the function is GetPtr1(int,int) and it’s return parameter is a pointer to
//function
{
if(a>b)
return &Subtract;
else
}

//The easier way could be :
// Solution using a typedef : Define a pointer to a function which is taking
// two floats and returns a float

typedef float(*ptrToFunc)(float, float);
//now we can use ptrToFunc as user defined datatype, see following code :

ptrToFunc GetPtr2(int a, int b)
{
if(a>b)
return &Subtract;
else
}

void Return_A_Function_Pointer()
{
ptrToFunc pt2Function = NULL;
pt2Function=GetPtr1(10,20); // get function pointer from function ’GetPtr1’
cout << (*pt2Function)(2, 4) << endl; // call function using the pointer
pt2Function=GetPtr2(’10,20); // get function pointer from function ’GetPtr2’
cout << (*pt2Function)(2, 4) << endl; // call function using the pointer
}

```

Following program will make everything clear :

Quote

How to Use Arrays of Function Pointers ?
Operating with arrays of function pointer is very interesting. This offers the possibility to select
a function using an index. The syntax appears difficult, which frequently leads to confusion. There are two
ways of how to define and use an array of function pointers in C and C++. The first way uses a typedef, the
second way directly defines the array. It’s up to us which way we prefer.
```// C
typedef int (*ptrToFunc)(float, char);
// illustrate how to work with an array of function pointers
void Array_Of_Function_Pointers()
{
// define arrays and initialise each element to NULL, <funcArr1> and <funcArr2> are arrays with 10 pointers to
//functions which return an int and take a float and a
//char
// first way using the typedef
ptrToFunc funcArr1[10] = {NULL};
// 2nd way directly defining the array
int (*funcArr2[10])(float, char) = {NULL};
funcArr1[0] = &SendIt;
funcArr1[1] = &SendIt2;
/* more assignments */
// calling a function using an index to address the function pointer
printf("%d\n", funcArr1[1](12, ’a’)); // short form
printf("%d\n", (*funcArr1[0])(12, ’a’)); // "correct" way of calling
}

// C++
// type-definition:
typedef int (MyClass::*ptrToMember)(float, char);
void Array_Of_Member_Function_Pointers()
{
// arrays with 10 pointers to member functions which return an int and take
// a float and a char
// first way using the typedef
ptrToMember funcArr1[10] = {NULL};
// 2nd way of directly defining the array
int (MyClass::*funcArr2[10])(float, char) = {NULL};
// assign the function’s address - ’SendIt’ and ’SendIt2’
funcArr1[0] = funcArr2[1] = &TMyClass::SendIt;
funcArr1[1] = funcArr2[0] = &TMyClass::SendIt2;
// calling a function using an index to address the member function pointer
MyClass instance;
cout << (instance.*funcArr1[1])(12, ’a’) << endl;
cout << (instance.*funcArr1[0])(12, ’a’) << endl;
}

```

Was that helpful . I hope It was...

#### Attached File(s)

Is This A Good Question/Topic? 0

## Replies To: Basics Of Function Pointers

### #2 spullen

• D.I.C Regular

Reputation: 10
• Posts: 356
• Joined: 22-March 07

Posted 14 April 2007 - 02:35 PM

I am new to c++, and I think I understand what a function pointer is from your tutorial, however I still have some questions. So as the name implies a function pointer is a pointer that points to a memory location of a function, and it acts as a variable, right? So what does this mean in terms of execution time, is it quicker then a normal function because it knows exactly where in memory the instruction for the method is?

### #3 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

Posted 17 April 2007 - 07:22 AM

spullen, on 15 Apr, 2007 - 03:05 AM, said:

So what does this mean in terms of execution time, is it quicker then a normal function because it knows exactly where in memory the instruction for the method is?

Well, function pointer may save on execution time but that is not the main purpose behind the use of function pointers. Function pointers are mainly used to get late binding, the situation where we have to decide which funtion to call at runtime.

so in case where we have 5-6 functions with same parameter list and we are supposed to call one of them with the parameters passed. This decision of calling one of these functions is dependant on the parameters which we are getting in.

the complexity rises when we are supposed to do the further execution depending on which function got called. To come over the situation we might try different ways like using variables as flags or passing values through functions. but all these options lead to nothing but more complexity.

So, we can use function pointer here. we will have one function pointer which will point to one of these function based on the input given. As I mentioned in tutorial you can even compare the function pointer with functions so you will not need to maintain which function you called runtime.

This is one of the benifits of function pointers.
Main purpose of function pointer is for callbacks or late bindings.
So whenever you use function pointer, just check that whether you really need it. [this implies to every feature of language actually ]

### #4 spullen

• D.I.C Regular

Reputation: 10
• Posts: 356
• Joined: 22-March 07

Posted 29 April 2007 - 10:56 AM

hmm, that makes sense. I guess I'll get more familiar with it when I have to use it more.

### #5 Xing

Reputation: 19
• Posts: 725
• Joined: 22-July 06

Posted 04 May 2007 - 02:44 AM

Excellent function pointers tutorial can be found here
http://www.newty.de/fpt/index.html

### #6 spullen

• D.I.C Regular

Reputation: 10
• Posts: 356
• Joined: 22-March 07

Posted 08 May 2007 - 08:29 AM

nice find

### #7 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 187
• Posts: 4,673
• Joined: 26-November 04

Posted 08 May 2007 - 11:15 PM

Also note that a lot of protection mechanisms use function pointers combined with other techniques such as Stack Execution and others.

This makes reverse engineering a lot tougher.

### #8 k.sangeeth

Reputation: 0
• Posts: 62
• Joined: 27-July 07

Posted 01 August 2007 - 05:25 AM

Xing, on 4 May, 2007 - 02:44 AM, said:

Excellent function pointers tutorial can be found here
http://www.newty.de/fpt/index.html

great link .. the world is still a good place to be ..
so many knowledgeable people and so much good will

### #9 Cupid_02000

Reputation: 0
• Posts: 2
• Joined: 03-June 08

Posted 09 July 2008 - 02:16 PM

Hey Amit,

It was really a great contribution from you ,it can be greater if you can walkthrough a code example and ignorant guys like me can understand that better.But no doubts it was a great post and you are doin a commendable job...waiting for your new posts.

Thanks,
cupid...

### #10 Tom9729

• Segmentation fault

Reputation: 181
• Posts: 2,642
• Joined: 30-December 07

Posted 10 July 2008 - 07:48 AM

If you ever plan on writing any kind of library using callbacks, you'll likely need to use function pointers.

### #11 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

Posted 23 July 2008 - 05:33 AM

Cupid_02000, on 10 Jul, 2008 - 02:46 AM, said:

Hey Amit,

It was really a great contribution from you ,it can be greater if you can walkthrough a code example and ignorant guys like me can understand that better.But no doubts it was a great post and you are doin a commendable job...waiting for your new posts.

Thanks,
cupid...

Thanks for the reply Cupid, I am happy that it helped you. I am having a heavy workload since last few months so not able to contribute with tutorials and snippets. But I will try to do that as soon as I get some time to breath.