ProgrammingHard
Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?
- A. return (x > y) - (x < y);
- B. return x - y;
- C. return x > y ? 1 : 0;
- D. return abs(x - y);
Correct answer: A. return (x > y) - (x < y);
x - y can overflow for values near INT_MIN and INT_MAX, which is undefined. The comparison (x > y) - (x < y) yields -1, 0 or 1 without any arithmetic overflow, and a plain x > y never returns a negative value.
More C Programming questions
- int m[3][4]; int f = &m[0][0]; Which expression refers to the same element as m[2][1]?
- int m[3][4]; What is sizeof(m) / sizeof(m[0][0])?
- int a[] = {1, 2}; int b[] = {3, 4}; int x = a, y = b; void swap(int p, int q) { int t = p; p = q; q = t; } After swap(&x, &y) runs, what…
- A recursive function is written as int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }. What is gcd(1071, 462)?
- Starting at n = 27, the loop while (n != 1) { n = (n % 2) ? 3 n + 1 : n / 2; steps++; } runs with int n. What is steps at the end?
- Using square-and-multiply on int values with a reduction modulo 1000 after each multiplication, what is 3^13 mod 1000?