Recap: Calculator Dispatch
Part of the Object Oriented Programming section of Coddy's C journey — lesson 37 of 61.
Challenge
EasyBuild a calculator using a dispatch table. You'll create an array of function pointers that maps operation codes to their corresponding functions, then use it to perform calculations.
Write a program that:
- Creates a
typedefcalledOperationfor a function pointer that takes twointparameters and returns anint - Defines four arithmetic functions:
add— returns a + bsub— returns a - bmul— returns a * bdivide— returns a / b (integer division)
- In
main, creates a dispatch table: an array of 4Operationfunction pointers, where index 0 is add, index 1 is sub, index 2 is mul, and index 3 is divide - Reads three inputs: two integers and an operation code (0-3)
- Uses the operation code to index into the dispatch table and call the appropriate function
- Prints the result
You will receive three inputs: the first number, the second number, and the operation code (0 for add, 1 for sub, 2 for mul, 3 for divide).
Your output should be a single integer—the result of the operation:
7In this example with inputs 10, 3, 1: the operation code 1 selects sub from the dispatch table, so we compute 10 - 3 = 7.
The key here is using array indexing to select the function—no if or switch statements needed. Your dispatch table should look like:
Operation ops[4] = {add, sub, mul, divide};Then call the function using: ops[code](a, b)
Try it yourself
#include <stdio.h>
// TODO: Create a typedef called 'Operation' for a function pointer
// that takes two int parameters and returns an int
// TODO: Define the four arithmetic functions: add, sub, mul, divide
int main() {
// Read input
int a, b, code;
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &code);
// TODO: Create the dispatch table (array of 4 Operation function pointers)
// Operation ops[4] = { ... };
// TODO: Use the operation code to call the appropriate function
// and store the result
int result;
// Output the result
printf("%d\n", result);
return 0;
}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