ProgrammingHardTCS NQT · Infosys pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
int (*fp)(int, int);
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main(void) {
    fp = add;
    int r1 = fp(3, 4);
    fp = sub;
    int r2 = fp(3, 4);
    printf("%d %d", r1, r2);
}
  1. A. 7 7
  2. B. 7 -1
  3. C. Compile-time error: fp cannot hold both add and sub
  4. D. -1 7

Correct answer: B. 7 -1

fp is a function pointer compatible with any function of type int(int,int); assigning add's or sub's address (functions decay to pointers automatically in this context, no & needed) and calling through fp dispatches to whichever function it currently holds. fp(3,4) with add gives 7; reassigned to sub, fp(3,4) gives 3-4=-1.

More C Programming questions

Exams that ask this topic