ProgrammingModerateTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}
int main(void) {
    int v[] = {9, 4, 7, 1};
    qsort(v, 4, sizeof v[0], cmp);
    int k = 7;
    int *f = bsearch(&k, v, 4, sizeof v[0], cmp);
    printf("%ld", (long)(f - v));
}
  1. A. 3
  2. B. 1
  3. C. 0
  4. D. 2

Correct answer: D. 2

After sorting, v is 1 4 7 9, so bsearch finds 7 at index 2 and the pointer difference is 2. The comparator returns -1, 0 or 1 without subtracting, so it cannot overflow.

More C Programming questions

Exams that ask this topic