ProgrammingHard
A middle index of a range [lo, hi] is needed for hi near INT_MAX. Which expression is safe?
- A. int mid = (lo + hi) / 2;
- B. int mid = (lo + hi) >> 1; with lo + hi overflowing
- C. int mid = lo + (hi - lo) / 2;
- D. int mid = hi / 2 + lo / 2 + 1;
Correct answer: C. int mid = lo + (hi - lo) / 2;
lo + hi can exceed INT_MAX and overflow. Computing lo + (hi - lo) / 2 never adds two large values, and hi - lo stays in range when lo <= hi.
More C Programming questions
- A scanf loop reads integers until the end of input. Which loop is correct when the input may end with a non-numeric token?
- A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?