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?

  1. A3
  2. B6
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. fill and use are functions defined elsewhere. Which of the following is a problem with the function above?
  2. Which of the following is true about the pointer returned by the function make above?
  3. In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?
  4. The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?
  5. In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?