Declaring Function Pointers
Part of the Object Oriented Programming section of Coddy's C journey — lesson 33 of 61.
So far, we've learned to simulate inheritance using struct embedding. But true polymorphism — where different objects respond differently to the same call — requires something more: function pointers.
A function pointer is a variable that stores the address of a function. Just like a regular pointer holds the address of data, a function pointer holds the address of executable code.
The syntax can look intimidating at first. To declare a function pointer, you specify the return type, then the pointer name in parentheses with an asterisk, followed by the parameter types:
int (*operation)(int, int);This declares a variable called operation that can point to any function that takes two int parameters and returns an int. The parentheses around *operation are crucial — without them, you'd be declaring a function that returns a pointer.
To assign a function to this pointer, simply use the function's name (without parentheses):
int add(int a, int b) {
return a + b;
}
int (*operation)(int, int);
operation = add; // Now operation points to addThe function name acts as its address. You can also use &add explicitly, but it's optional — both forms are equivalent in C.
Challenge
EasyLet's practice declaring function pointers and assigning functions to them. You'll create a simple math operation system where a function pointer can hold different arithmetic functions.
Write a program that:
- Defines two functions:
multiply— takes twointparameters and returns their productsubtract— takes twointparameters and returns the first minus the second
- In
main, declares a function pointer variable calledoperationthat can point to functions taking twointparameters and returning anint - Reads three inputs: two integers and an operation code (1 for multiply, 2 for subtract)
- Based on the operation code, assigns the appropriate function to your
operationpointer - Prints the name of the assigned operation, then prints the result of calling the function through the pointer
You will receive three inputs: the first number, the second number, and the operation code (1 or 2).
Your output should look like this:
Operation: multiply
Result: 35Where multiply is the operation name (or subtract if code is 2), and 35 is the result of calling the function through your pointer (in this case, 5 × 7).
Remember: to declare the function pointer, you need the return type, the pointer name in parentheses with an asterisk, and the parameter types. To assign a function, use just the function name without parentheses.
Cheat sheet
A function pointer is a variable that stores the address of a function, enabling polymorphism by allowing different functions to be called through the same pointer.
Declaring a Function Pointer
The syntax specifies the return type, pointer name with asterisk in parentheses, and parameter types:
int (*operation)(int, int);This declares operation as a pointer to any function that takes two int parameters and returns an int. The parentheses around *operation are essential.
Assigning a Function to a Pointer
Use the function name without parentheses:
int add(int a, int b) {
return a + b;
}
int (*operation)(int, int);
operation = add; // operation now points to addThe function name acts as its address. You can also use &add explicitly, but it's optional.
Try it yourself
#include <stdio.h>
// TODO: Define the multiply function here
// TODO: Define the subtract function here
int main() {
int num1, num2, code;
// Read input
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &code);
// TODO: Declare a function pointer called 'operation' that can point to
// functions taking two int parameters and returning an int
// TODO: Based on the operation code (1 for multiply, 2 for subtract),
// assign the appropriate function to your operation pointer
// TODO: Print the operation name and the result
// Format:
// Operation: <name>
// Result: <result>
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box7Function Pointers
Declaring Function PointersCalling Function PointersTypedef for Function PointersPassing Functions as ArgumentsRecap: Calculator Dispatch2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy