CPA-21-02 practice question 21 of 35

What will happen when you attempt to compile and run the following code? #include using namespace std; int main() { const char *s; char str[] = "Hello "; s = str; while(*s) { cout

Full set: 257 questions
Answer options
A: It will print:"el " Correct answer
B: The code will not compile.
C: It will print:"Hello "
D: It will print garbage value
Correct Answer:
A. It will print:"el "
Explanation

The pointer s is initialized to point to the first character of "Hello " ('H'). In the first iteration, ++s pre-increments the pointer to 'e' and prints it. Then, s++ post-increments the pointer to the first 'l' (the dereferenced value is discarded). In the second iteration, the loop condition checks 'l' (true), ++s pre-increments to the second 'l' and prints it, and s++ post-increments to 'o'. In the third iteration, the condition checks 'o' (true), ++s pre-increments to ' ' (space) and prints it, and s++ post-increments to \0. The loop terminates, outputting "el ".

Why Incorrect

B: The code is syntactically valid. s is a non-const pointer to const data, so modifying the pointer via s++ is allowed. C: The double increment inside the loop body skips characters, so it will not print the full string. D: The pointer arithmetic is well-defined and stays within the bounds of the null-terminated string, so no garbage values are printed.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 8.3.2 [expr.post.incr] (Postfix increment and decrement).

2. ISO/IEC 14882:2017 (C++17 Standard), Section 8.3.1 [expr.pre.incr] (Prefix increment and decrement).

Scroll to Top