Introduction / Context:
In C, a pointer declared as const char * may point to a character array, and you are allowed to move the pointer and read characters through it; the const qualifier forbids writing through the pointer, not reassigning the pointer itself. This question checks understanding of pointer iteration over a NUL-terminated string using a simple while loop that stops at the terminating '\0'.
Given Data / Assumptions:
- const char *s = ""; then char str[] = "Hello"; s = str;
- Loop: while (*s) printf("%c", *s++);
- Standard C string semantics: arrays are NUL-terminated.
Concept / Approach:
- The condition *s is true for any non-zero character; it becomes false at the NUL terminator.
- The expression *s++ prints the current character and then advances the pointer to the next character (post-increment of the pointer).
- No writes occur through s, so const-correctness is respected.
Step-by-Step Solution:
Start: s points to 'H' → print 'H', advance to 'e'.Next: print 'e', advance to 'l'.Then: print 'l', advance to second 'l'.Then: print 'l', advance to 'o'.Finally: print 'o', advance to '\0' → loop ends.
Verification / Alternative check:
Replacing the loop with puts(str) would also print 'Hello' followed by a newline; our loop prints without adding a newline.
Why Other Options Are Wrong:
- Error/Undefined behavior: no invalid operations occur; only reads and pointer increments.
- 'H' or 'Hel': would require an early exit; the loop continues until NUL.
Common Pitfalls:
- Misreading *s++ as (*s)++ (which would attempt to modify the character); precedence rules mean it is *(s++), a pointer increment, not a character increment.
- Forgetting that the empty string "" initially is harmless since s is later reassigned to str before use.
Final Answer:
Hello
Discussion & Comments