ProgrammingVery hard
A struct array holds records with an int key; the program calls qsort with the comparator (int)(a->key - b->key) for keys near INT_MAX and INT_MIN. What is the correct description of the behaviour?
- A. The result is always negative and the sort is correct
- B. Signed overflow is undefined, so the sign of the result cannot be relied on
- C. The result is always zero, so the sort does nothing
- D. The comparison is safe because the difference is cast to int
Correct answer: B. Signed overflow is undefined, so the sign of the result cannot be relied on
The subtraction itself overflows when the keys differ by more than INT_MAX, which is undefined behaviour. The cast does not fix it.
More C Programming questions
- A bsearch call uses a key of type int but the array holds struct records with an int field. What is the correct way to compare?
- Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?
- 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)?