Keil Logo

Function Pointers

Function pointers are one of the most difficult aspects of C to understand and to properly utilize. Most problems involving function pointers are caused by improper declaration of the function pointer, improper assignment, and improper dereferencing.

The following brief example demonstrates how to declare a function pointer (f), how to assign function addresses to it, and how to call the functions through the pointer. The printf routine is used for example purposes when running the µVision Debugger to simulate program execution.

#pragma code symbols debug oe

#include <reg51.h>       /* special function register declarations */
#include <stdio.h>       /* prototype declarations for I/O functions */

void func1(int d) {     /* function #1 */
  printf("In FUNC1(%d)\n", d);
}

void func2(int i) {     /* function #2 */
  printf("In FUNC2(%d)\n", i);
}

void main(void) {
  void (*f)(int i);     /* Declaration of a function pointer */
                          /* that takes one integer arguments */
                          /* and returns nothing */

  SCON  = 0x50;          /* SCON: mode 1, 8-bit UART, enable rcvr */
  TMOD |= 0x20;          /* TMOD: timer 1, mode 2, 8-bit reload */
  TH1   = 0xf3;          /* TH1:  reload value for 2400 baud */
  TR1   = 1;             /* TR1:  timer 1 run */
  TI    = 1;             /* TI:   set TI to send first char of UART */

  while( 1 ) {
    f = (void *)func1;  /* f points to function #1 */
    f(1);
    f = (void *)func2;  /* f points to function #2 */
    f(2);
  }
}

Note

  • Because of the limited stack space of the 8051, the linker overlays function variables and arguments in memory. When you use a function pointer, the linker cannot correctly create a call tree for your program. For this reason, you may have to correct the call tree for the data overlaying. Use the OVERLAY directive with the linker to do this.
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.