Function pointer syntax (e.g., void (*ptr)(int)) is notoriously hard to read. In professional firmware, we use typedef or using to create an alias for the function pointer type. This makes APIs cleaner and allows passing "Strategies" or "Algorithms" as simple arguments.
Your task is to implement a Calculator that can swap its internal math algorithm at runtime.
MathOp for a pointer to a function that takes two ints and returns an int.int add(int a, int b): Returns a + b.int multiply(int a, int b): Returns a * b.Calculator:MathOp current_op (Initialize to add by default).void setMode(MathOp op): Updates the internal pointer.void compute(int a, int b): Calls the pointer and prints Result: <value>.Program Flow:
Calculator (default mode is ADD).N.N times.cmd.cmd is "MODE_ADD": call calc.setMode(add).cmd is "MODE_MUL": call calc.setMode(multiply).cmd is "CALC": read two integers a, b and call calc.compute(a, b).Input Format:
N.N lines: String cmd, optionally followed by values.Output Format:
Result: <value>Example:
Example 1
Input:
3
CALC 10 10
MODE_MUL
CALC 10 10Output:
Result: 20
Result: 100Constraints:
typedef (or using) to define the function pointer type.switch-case inside compute() to decide the operation.
Input
3 CALC 10 10 MODE_MUL CALC 10 10
Expected Output
Result: 20 Result: 100