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);
}- A. 7 7
- B. 7 -1
- C. Compile-time error: fp cannot hold both add and sub
- 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
- Assume a 64-bit LP64 ABI. What is printed? c void process(int data, int len) { for (int i = 0; i < len; i++) data[i] = 2; } int main(void)…
- Assume a 64-bit LP64 ABI. What is printed? c int global = 10; int getPtr(void) { return &global; } int main(void) { int p = getPtr(); p =…
- Assume a 64-bit LP64 ABI. What is printed? c struct Point { int x, y; }; void move(struct Point p, int dx, int dy) { p->x += dx; p->y +=…
- Assume a 64-bit LP64 ABI. What is printed? c void modify(int x) { x = 100; } void modifyPtr(int x) { x = 100; } int main(void) { int a =…
- Assume a 64-bit LP64 ABI. What is printed? c int allocateArray(int n) { int arr = malloc(n sizeof(int)); for (int i = 0; i < n; i++)…
- Assume a 64-bit LP64 ABI. What is printed? c int compare(const void a, const void b) { return (const int )a - (const int )b; } int…