ProgrammingHardAccenture · Capgemini

What is printed?

What is printed?
typedef int (*Op)(int);
int twice(int x) { return 2 * x; }
int plus3(int x) { return x + 3; }
int apply(Op f, Op g, int x) { return f(g(f(x))); }
int main(void) {
    printf("%d %d", apply(twice, plus3, 1), apply(plus3, twice, 1));
}
  1. A. 8 11
  2. B. 10 11
  3. C. 11 10
  4. D. 10 8

Correct answer: B. 10 11

apply runs f, then g, then f again. twice, plus3, twice on 1: 2 → 5 → 10. plus3, twice, plus3 on 1: 4 → 8 → 11. Swapping the roles of f and g changes the result because the operations do not commute.

More C Programming questions

Exams that ask this topic