ProgrammingHard
int cmp(const void *a, const void *b) { return ((const struct Rec *)a)->k - ((const struct Rec *)b)->k; } Which statement is correct about this comparator with keys in [0, 100]?
- A. It is safe for these keys, since the subtraction cannot overflow
- B. It is undefined for every input because of the cast
- C. It returns the wrong sign because subtraction is reversed
- D. It is undefined for keys above 1000 only
Correct answer: A. It is safe for these keys, since the subtraction cannot overflow
With keys in [0, 100] the difference is small, so no overflow occurs. The subtraction gives a negative, zero or positive result as qsort expects.
More C Programming questions
- struct Score { char name[5]; int pts; }; struct Score s = {"Amy", 7}; printf("%d", (int)strlen(s.name)); What is printed?
- struct W { int x; }; struct W w1 = {3}, w2 = {3}; printf("%d", w1.x == w2.x && memcmp(&w1, &w2, sizeof w1) == 0); What is printed (no…
- struct Pack { char a; int b; } p = {'x', 5}; unsigned char raw = (unsigned char )&p; printf("%d", raw[0] == 'x'); What is printed?
- struct Bits { int f : 4; }; struct Bits b; b.f = 3; printf("%d", b.f); What is printed in C for a signed 4-bit field holding 3?
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xB5, y = 0x4E, z = x ^ y, c = 0; while (z) { z &= z - 1; c++; }…
- What is printed? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint8t v = 0; v |= 1u << 3; v |= 1u <<…