Indexing tricks and side effects in C: determine the precise characters printed by this code involving pre/post increment and the i[s] notation.
#include
int main()
{
static char s[25] = "The cocaine man";
int i = 0;
char ch;
ch = s[++i]; printf("%c", ch);
ch = s[i++]; printf("%c", ch);
ch = i++[s]; printf("%c", ch);
ch = ++i[s]; printf("%c", ch);
return 0;
}
Choose the exact 4-character output.
-
Ahhe!
-
Bhe c
-
CThe c
-
DHhec
-
ENone of the above
Answer
Correct Answer: hhe!
Explanation
Introduction / Context:This problem explores array indexing equivalence, pre/post-increment behavior, and modification of characters through lvalues. The expression i[s] is the same as s[i]; both rely on pointer arithmetic. Understanding evaluation order and side effects is essential to predict the output.
Given Data / Assumptions:
- s = "The cocaine man" with indices: T(0), h(1), e(2), space(3), c(4), o(5), c(6), a(7), i(8), n(9), e(10), space(11), m(12), a(13), n(14).
- i starts at 0.
- Pre-increment ++i updates i before indexing; post-increment i++ uses the current value, then increments.
- Expression i[s] equals s[i].
Concept / Approach:Track i carefully and know what character each operation reads or writes. The last operation ++i[s] increments the stored character at position i and yields the incremented character, altering the array content.
Step-by-Step Solution:ch = s[++i]; i becomes 1; s[1] = 'h' → prints h.ch = s[i++]; uses i = 1 then increments to 2; s[1] = 'h' → prints h.ch = i++[s]; same as s[i++]; uses i = 2 then increments to 3; s[2] = 'e' → prints e.ch = ++i[s]; i is 3; i[s] is s[3] (space). ++ applied to the character increments space (ASCII 32) to '!' (ASCII 33), stores back, and yields '!' → prints !.
Verification / Alternative check:Insert debugging prints of i and character codes; you will see i evolve as 1, 2, 3 and the final modification at index 3. After execution, s becomes "The!cocaine man" due to the mutated space.
Why Other Options Are Wrong:'he c', 'The c', 'Hhec': do not match the exact sequence of characters and increments produced by the operations.
Common Pitfalls:Thinking i[s] is different from s[i]; forgetting that ++ on a char lvalue changes the stored character; mixing up pre vs post increment.
Final Answer:hhe!