1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Advanced Pointers

By David Bolton, About.com

6 of 8

An Example with Function Pointers

In Example 2, this code uses the function pointer

Download example 2

if (head ) {
  pointerToFunction = ShowEvenKeys;
  ProcessList( head ) ;
  pointerToFunction = ShowOddKeys;
  ProcessList( head ) ;
}
There are two functions which match the function pointers definition. ShowOddKeys() and ShowEvenKeys(). By matching I mean that both functions pass in the same parameters and return the same type as the definition. This example iterates through the list twice, calling the assigned function pointer. On the first pass it outputs
KEYID:2
KEYID:4
KEYID:6
KEYID:8
KEYID:10
KEYID:12
KEYID:14
..
KEYID:100
and then
KEYID:1
KEYID:3
KEYID:5
KEYID:7
KEYID:9
..
KEYID:99

void ProcessList( pNode node) {
  pElement element=0;
  while (node) {
      element = node->data;
      if (pointerToFunction)
          pointerToFunction(element) ;
    node = node->next;
    }
}
ProcessList checks that the function pointer has been assigned a function then calls it, just as if it were a normal function.

Points to Note

  • Easy Function declaration- Declare the function then add (* ) around the function name.
  • You don't need & to get the address of a function, this is the same as an array.
  • Functions must match in same number and types of parameters and the same return type but you can use void *.
  • Call the function via the function pointer just like calling a function directly. eg fp(x) ;

On the next page : Other Uses of a Function Pointer

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. An Example with Function Pointers

©2009 About.com, a part of The New York Times Company.

All rights reserved.