CodeBlanks Logo Icon CodeBlanks

Function pointer definition

  • C course
  • Intermediate
  • Lesson 24/116
  • 5 min

Learn function pointer syntax and types.

Function pointer types

A function pointer is a variable holding a function's address. The declaration is a return type, a parenthesized star and name, then the parameter list.

Example: int (*fp)(int, int) = add;. Here fp is a pointer to a function taking two ints and returning int. Parentheses matter: writing int *fp(int, int) declares a function returning int *. Parentheses are required to mark it as a pointer. The return and parameter types must match the function signature exactly.

Type matching

When assigning to a function pointer, the return type and parameter list must match exactly. Otherwise the compiler warns and the behavior is undefined.

Example: for int add(int, int); write int (*fp)(int, int) = add;. But int (*fp)(int) = add; mismatches parameter count. Likewise double (*fp)(int, int) = add; mismatches return type. The pointer type carries the function signature as a contract; that's why it's long but safe.

Practice Declare a function pointer

Write int add(int a, int b) that returns a + b. Declare a pointer with int (*fp)(int, int) = add; and assign it to add. Print the result of fp(3, 4) with printf("%d\n", fp(3, 4));.

Starter code

main.c
#include <stdio.h>

// Write the add function
// Declare the fp pointer
// Call fp and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main(void) {
    int (*fp)(int, int) = add;
    printf("%d\n", fp(3, 4));
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a pointer to a function returning int and taking two ints?

  • int *fp(int, int);
  • int (*fp)(int, int); Correct answer
  • int fp*(int, int);
  • (int *)fp(int, int);

Explanation: Parentheses make fp a pointer; int *fp(int, int) is a function declaration.

2 Two-parameter function pointer

Question
int (____)(int, int) = add;
Answer
int (*fp)(int, int) = add;

Explanation: *fp inside the parentheses forms the pointer variable.

3 Match the function pointer parts

Term Meaning
int Return type
(*fp) Pointer variable
(int, int) Parameter list
= add Assignment

All lessons in Intermediate