ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int inc(int x) { return x + 1; }
int dbl(int x) { return x * 2; }
int sqr(int x) { return x * x; }
int apply(int (*f[])(int), int n, int x) {
    return n == 0 ? x : f[n - 1](apply(f, n - 1, x));
}
int main(void) {
    int (*t[])(int) = {inc, dbl, sqr, inc};
    printf("%d %d", apply(t, 4, 2), apply(t + 1, 2, 3));
}
  1. A. 19 36
  2. B. 37 18
  3. C. 37 36
  4. D. 37 64

Correct answer: C. 37 36

The recursion applies f[0] innermost and f[n − 1] outermost, i.e. the table is applied left to right: inc(2) = 3, dbl → 6, sqr → 36, inc → 37. A function-pointer array parameter is just a pointer, so t + 1 is a table starting at dbl; with n = 2 it computes sqr(dbl(3)) = 36. '19' applies the table right to left (inc, sqr, dbl, inc); '18' does dbl(sqr(3)).

More C Programming questions

Exams that ask this topic