ProgrammingHardGATE CS · Campus placements
A qsort comparator is written as return *(const int *)a - *(const int *)b; Which statement is true?
- A. It is correct for every pair of int values, because overflow always wraps
- B. It can invoke undefined behaviour when the subtraction overflows int, for example 2000000000 minus -2000000000
- C. It is always correct because qsort subtracts the values itself
- D. It fails only when the array holds unsigned values
Correct answer: B. It can invoke undefined behaviour when the subtraction overflows int, for example 2000000000 minus -2000000000
Signed int overflow is undefined behaviour, and the difference of two large-magnitude ints can exceed INT_MAX. Comparators should compare with < and > instead of subtracting.
More C Programming questions
- Which statement about the standard library function qsort is true?
- char names[] holds char pointers to strings and must be sorted alphabetically with qsort(names, n, sizeof names[0], cmp). Which comparator…
- int f(int n) { return n < 2 ? 1 : f(n - 1) + f(n - 2); } How many calls to f happen in total, counting the first call, when evaluating f(5)?
- A recursive Tower of Hanoi solution moves n disks, one at a time, with the rule that a larger disk never sits on a smaller one. How many…
- The Ackermann function is defined as A(0,n) = n+1, A(m,0) = A(m-1,1), and A(m,n) = A(m-1, A(m,n-1)) for m, n > 0. What is A(2,3)?
- int a[5] = {10, 20, 30, 40, 50}; int p = a + 1, q = a + 4; printf("%td %d", q - p, (p + 2)); prints what?