What is Function pointer?

A pointer whose value is the address of a function. It is declared including the argument and return types, as in int (*fp)(int, int) = add; and the function it points to is called with fp(1, 2) or (*fp)(1, 2). An array of function pointers forms a table that selects processing by number. Function pointers are used for callbacks such as the comparison function passed to qsort, interrupt vector tables, and the handlers of each state in a state machine. In machine code, the call becomes an indirect call that jumps to an address held in a register.

Japanese name: 関数ポインタ

Function pointer appears in 3 practice questions across 2 topics, including ISA & Assembly, C Programming Basics.

Field: C Programming Basics

Try it: questions about Function pointer

How is a call through a C function pointer, "(*fp)(x)", generally performed in RISC-V?

  1. AThe function address is placed in a register, and jalr jumps to that register's address
  2. Bjal jumps with the function address written as an immediate
  3. Cbeq compares with the function address and jumps if equal
Show answer and explanation

Answer: A. The function address is placed in a register, and jalr jumps to that register's address

The target of a function pointer is not known until run time, so jal, whose target is written in the instruction, cannot be used. Instead the pointer value is loaded into a register and the code jumps to it with, for example, "jalr ra, 0(t0)", leaving the return address in ra. Calls to C++ virtual functions and shared-library functions are similar indirect calls. Because the target can change, CPUs predict it with an indirect branch predictor.

Function pointer in the explanations

Questions that mention Function pointer (3)

  1. How is a call through a C function pointer, "(*fp)(x)", generally performed in RISC-V?
  2. Which of the following is the output when the program above, which uses an array of function pointers, is executed?
  3. Which real instruction executes the RISC-V pseudo-instruction "ret"?

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

Related terms

Pointer Return address Array Pseudo-instruction Alignment and padding Bit-field Buffer overflow Dangling pointer Dynamic memory allocation Integer promotion

Back to the glossary