C Programming Basics
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int main(void) {
int (*op[2])(int, int) = {add, mul};
int r = 1;
for (int i = 0; i < 2; i++)
r = op[i](r, 3);
printf("%d\n", r);
return 0;
}Which of the following is the output when the program above, which uses an array of function pointers, is executed?
- A3
- B6
- C12
Show answer and explanation
Answer: C. 12
op is an array of two pointers to functions that take two ints and return an int; op[0] holds the address of add and op[1] that of mul. op[i](r, 3) calls the function that the pointer points to. With i = 0, r = add(1, 3) = 4, and with i = 1, r = mul(4, 3) = 12. Function pointers are used for dispatch tables, interrupt vectors, callbacks and so on.
- A. This is the value obtained by computing from r = 1 each time, so that only the last mul(1, 3) = 3 remains.
- B. This is the value obtained by calling mul first and add second (1 × 3 = 3, 3 + 3 = 6).
- C. Correct. add(1, 3) = 4, then mul(4, 3) = 12.