Difficulty: Medium
Correct Answer: 8
Explanation:
Introduction / Context:
This C++ program performs a recursive scan over a C-style string using a static index variable. It stops when the currently inspected character matches the target and then computes a value from the suffix length. The key concepts are pointer arithmetic, static local variables, and how pre/post increments affect the index used in expressions.
Given Data / Assumptions:
i++
.
Concept / Approach:
The expression txtMsg[i++] == ch
compares the current character, then increments i
. On the match at index 8, i
becomes 9. The function returns strlen(txtMsg + i) - i
, i.e., the length of the suffix starting at position 9 minus 9. If the total length is N
, the suffix length is N - 9
, so the return value is (N - 9) - 9 = N - 18
.
Step-by-Step Solution:
Verification / Alternative check:
Manually counting characters or printing strlen(txtMsg)
confirms N = 26. The suffix beginning at index 9 ("o CuriousTab.com!") has length 17; 17 - 9 = 8, consistent with the formula.
Why Other Options Are Wrong:
i++
in the condition or miscount the overall string length.
Common Pitfalls:
Forgetting that i
is static (it persists across recursive calls), and misunderstanding that i++
increments after the comparison, so the returned expression uses i = 9
on the first match.
Final Answer:
8
Discussion & Comments