Function Pointers in C
Functions also live in memory, so they have addresses too. A function pointer stores the address of a function, and you can call the function through it.
Why would you want that? So a program can choose at run time which function to run: a calculator picking +, −, × or ÷, a sort that can order up or down, or a button that runs whatever action you give it. In this lesson you will learn the syntax step by step, then build a calculator menu and a callback.
What You Will Learn
- What a function pointer is.
- How to declare and assign a function pointer.
- How to call a function through a pointer.
- How to pass a function to another function (callback).
- How to use an array of function pointers.
- How
qsortuses a function pointer.
What is a Function Pointer in C?
Exam definition: A function pointer is a pointer that stores the address of a function. It is declared with the function's return type and parameter types, e.g. int (*fp)(int, int);, and the function is called through it as fp(a, b) or (*fp)(a, b).
Memory trick: A function pointer is a TV remote's programmable button. You decide which channel (function) the button stores. Pressing the button (calling the pointer) runs whatever was stored. The button must match the TV: same return type and parameters.
Syntax of a Function Pointer
int add(int a, int b); /* a function */
int (*fp)(int, int); /* fp: pointer to a function taking
(int, int) and returning int */
fp = add; /* or fp = &add; (same thing) */
int r = fp(3, 4); /* call through the pointer */
int s = (*fp)(3, 4); /* older style, same result */
Build the declaration in 3 steps
- Write the function's prototype:
int add(int a, int b); - Replace the name with
(*fp):int (*fp)(int a, int b); - Parameter names are optional:
int (*fp)(int, int);
The brackets around *fp are essential. int *fp(int, int); declares a function returning int *, not a pointer.
Example 1: Calling Functions Through a Pointer
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int main(void)
{
int (*op)(int, int); /* function pointer */
op = add;
printf("op = add : 12, 4 -> %d\n", op(12, 4));
op = subtract;
printf("op = subtract : 12, 4 -> %d\n", op(12, 4));
op = &multiply; /* & is optional */
printf("op = multiply : 12, 4 -> %d\n", (*op)(12, 4));
return 0;
}
Output
op = add : 12, 4 -> 16 op = subtract : 12, 4 -> 8 op = multiply : 12, 4 -> 48
Code Explanation
int (*op)(int, int);declaresopas a pointer to any function that takes two ints and returns an int.op = add;stores the address ofadd. A function name alone (without brackets) gives its address, just as an array name gives its base address.op(12, 4)calls whichever functionopcurrently points to. The same line of code runs different functions.(*op)(12, 4)is the older style; both are correct.
How Callbacks Work
A callback is a function you pass to another function, so that function can "call you back" at the right moment. The receiving function decides when; you decide what.
apply_to_all(arr, n, double_it)
|
|-- for each element: arr[i] = double_it(arr[i]) <- "calls back"
apply_to_all(arr, n, square) same loop, different action
Example 2: Callback Function and Calculator Menu
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }
int double_it(int x) { return x * 2; }
int square(int x) { return x * x; }
/* callback: action is a pointer to a function int -> int */
void apply_to_all(int arr[], int n, int (*action)(int))
{
int i;
for (i = 0; i < n; i++)
arr[i] = action(arr[i]);
}
void print(const int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main(void)
{
int nums[] = {1, 2, 3, 4};
int (*menu[4])(int, int) = {add, subtract, multiply, divide};
const char *names[4] = {"Add", "Subtract", "Multiply", "Divide"};
int choice;
apply_to_all(nums, 4, double_it);
printf("Doubled : ");
print(nums, 4);
apply_to_all(nums, 4, square);
printf("Squared : ");
print(nums, 4);
printf("Calculator on 20 and 5:\n");
for (choice = 0; choice < 4; choice++)
printf(" %d. %-8s = %d\n", choice + 1, names[choice], menu[choice](20, 5));
return 0;
}
Output
Doubled : 2 4 6 8 Squared : 4 16 36 64 Calculator on 20 and 5: 1. Add = 25 2. Subtract = 15 3. Multiply = 100 4. Divide = 4
int (*action)(int)as a parameter lets the caller choose the operation.apply_to_alldoesn't know or care which one.int (*menu[4])(int, int)is an array of 4 function pointers.menu[choice](20, 5)picks a function by number, which replaces a longswitch.- In a real menu program,
choicewould come fromscanf; check it's in range before callingmenu[choice - 1].
Real Use: qsort from stdlib.h
The library's qsort can sort any type because you give it a comparison function pointer:
#include <stdio.h>
#include <stdlib.h>
int descending(const void *a, const void *b)
{
return *(const int *)b - *(const int *)a; /* b - a: big first */
}
int main(void)
{
int marks[] = {56, 91, 73, 88, 64};
int i;
qsort(marks, 5, sizeof(int), descending);
for (i = 0; i < 5; i++)
printf("%d ", marks[i]);
printf("\n");
return 0;
}
91 88 73 64 56
The const void * parameters are generic pointers (next lesson); we cast them back to int *.
Important Points to Remember
- A function pointer stores the address of a function.
- Syntax: return_type (*name)(parameter types);
- The brackets around *name are required.
- A function name alone gives its address:
fp = add; - Call with fp(args) or (*fp)(args).
- Uses: callbacks, menus (array of function pointers), qsort, event handlers.
- The pointer's type must match the function's signature.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
int *fp(int, int); | Declares a function returning int * | int (*fp)(int, int); |
fp = add(2, 3); | Stores the result 5, not the function | fp = add; |
| Pointer type doesn't match the function | Warning; wrong results or crash | Match return and parameter types |
| Calling an unassigned function pointer | Crash | Initialize it (or to NULL and check) |
| Menu index from user not checked | Calls a random address | Check the range first |
Function Pointers Practice Questions
- Declare a pointer to a function that takes a float and returns a float.
- What is the difference between
int (*f)(int)andint *f(int)? - What is a callback function?
- Declare an array of 3 pointers to functions of type
void f(void). - Why does
qsorttake a function pointer?
Show answers
float (*fp)(float);- The first is a pointer to a function returning int; the second is a function returning an int pointer.
- A function passed as an argument to another function, which calls it at the right time.
void (*arr[3])(void);- So it can sort any data type in any order: you supply how two elements compare.
Coding Exercise
Write int count_if(const int arr[], int n, int (*test)(int)) that counts elements for which test returns true. Use it with is_even and is_positive on {-4, 7, 0, 12, -9, 6}.
Show solution
#include <stdio.h>
int is_even(int x) { return x % 2 == 0; }
int is_positive(int x) { return x > 0; }
int count_if(const int arr[], int n, int (*test)(int))
{
int i, count = 0;
for (i = 0; i < n; i++)
if (test(arr[i]))
count++;
return count;
}
int main(void)
{
int a[] = {-4, 7, 0, 12, -9, 6};
printf("Even : %d\n", count_if(a, 6, is_even));
printf("Positive: %d\n", count_if(a, 6, is_positive));
return 0;
}
Even : 4 Positive: 3
Quick Quiz: Function Pointers (MCQ)
-
Correct declaration of a pointer to
int f(char):A)
int *p(char);B)int (*p)(char);C)int p*(char);D)(int *)p(char); -
After
int (*p)(int, int) = add;, which calls add?A)
p(1, 2)B)(*p)(1, 2)C) Both D) Neither -
A function passed as an argument to another function is called a:
A) Recursive function B) Callback C) Macro D) Inline function
-
void (*f[5])(int);is:A) A function returning 5 pointers B) An array of 5 function pointers C) A pointer to an array D) Invalid
-
Which library function uses a comparison function pointer?
A)
printfB)strlenC)qsortD)malloc
Show answers
- B:
int (*p)(char); - C: both.
- B: callback.
- B: an array of 5 function pointers.
- C:
qsort.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Function pointer | Stores the address of a function |
|---|---|
| Syntax | int (*fp)(int, int); |
| Assign | fp = add; (no brackets after add) |
| Call | fp(a, b) or (*fp)(a, b) |
| int *fp(int) | Function returning int *, not a pointer |
| Array of them | int (*menu[4])(int, int); |
| Uses | Callbacks, menus, qsort |
Frequently asked questions
- What is a function pointer?
- A pointer that holds the address of a function so the function can be called through it.
- What is a callback function in C?
- A function passed as an argument (via a function pointer) that the other function calls later.
- Why are function pointers useful?
- They let a program choose the function at run time: menus, generic sorting, event handling.
Remember
- Function pointer = programmable remote button.
- Declaration: take the prototype, replace the name with (*name).
Next Topic
Next lesson: Special Types of Pointers in C. You will learn NULL, void, wild and dangling pointers, and how to stay safe from pointer bugs.