ProgrammingHardProduct company OA

What is printed?

What is printed?
struct Shape { int w, h; int (*area)(struct Shape *); };
int rect(struct Shape *s) { return s->w * s->h; }
int tri(struct Shape *s)  { return s->w * s->h / 2; }
int main(void) {
    struct Shape a[] = {{3, 4, rect}, {3, 5, tri}, {2, 2, rect}};
    int t = 0;
    for (int i = 0; i < 3; i++) t += a[i].area(&a[i]);
    printf("%d", t);
}
  1. A. 22
  2. B. 24
  3. C. 23
  4. D. 31

Correct answer: C. 23

Each struct carries its own function pointer, a hand-made version of virtual dispatch. rect gives 12 and 4; tri gives 15 / 2 = 7 in integer division. 12 + 7 + 4 = 23. '24' rounds 7.5 up; '31' treats every shape as a rectangle.

More C Programming questions

Exams that ask this topic