ProgrammingHardProduct company OA

What is printed?

What is printed?
enum Op { ADD, SUB, MUL };
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int main(void) {
    int (*tbl[])(int, int) = {[MUL] = mul, [ADD] = add, [SUB] = sub};
    printf("%d", tbl[SUB](tbl[MUL](3, 4), tbl[ADD](1, 2)));
}
  1. A. 7
  2. B. 9
  3. C. 1
  4. D. 15

Correct answer: B. 9

Designated initialisers place each function at the index of its enumerator, whatever order they are written in, so tbl[SUB] is sub. The call is sub(mul(3, 4), add(1, 2)) = 12 − 3 = 9. Reading the list positionally (mul, add, sub) would give add(sub(3, 4), mul(1, 2)) = 1.

More C Programming questions

Exams that ask this topic