ProgrammingVery hardProduct company OA
An array of `int` that may contain any values from INT_MIN to INT_MAX is sorted with `qsort`. With `int x = *(const int *)a, y = *(const int *)b;`, which return statement gives a comparator that is correct for ALL inputs?
- A. return x - y;
- B. return x > y;
- C. return (x > y) - (x < y);
- D. return (unsigned)x - (unsigned)y;
Correct answer: C. return (x > y) - (x < y);
qsort needs a negative, zero or positive result that is a consistent total order. (x > y) − (x < y) yields exactly −1, 0 or 1 with no arithmetic on the values. x − y overflows (undefined behaviour) when the operands are far apart, e.g. INT_MIN − 1; in practice it wraps and reports the wrong sign. x > y never returns a negative value, so 'less' and 'equal' are indistinguishable and the order is inconsistent. The unsigned difference wraps modulo 2³² and its conversion back to int gives the wrong sign for the same far-apart pairs.
More C Programming questions
- What is printed? c int a[] = {4, 8, 15, 16, 23}; printf("%zu %d", sizeof(a) / sizeof(a[0]), a[sizeof(a) / sizeof(a[0]) - 1]);
- What is printed? c printf("%d %d %d", 5 > 3 && 2 > 4, !0, !!7);
- What is printed? c int a = 5, b = 3; a = a ^ b; b = a ^ b; a = a ^ b; printf("%d %d", a, b);
- What is printed? c printf("%d %d %d", strcmp("abc", "abd") < 0, strcmp("ab", "abc") < 0, strncmp("abcx", "abcy", 3) == 0);
- What is printed? c int i = 3.99; int j = -3.99; int k = (int)(0.29 100); printf("%d %d %d", i, j, k);
- What is printed? c / 4-byte int with 4-byte alignment / struct S { int a; char b; } arr[5]; printf("%td %td", &arr[4] - &arr[1], (char…