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 questionsThe 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 ".
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.
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).
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 1What happens when you attempt to compile and run the following code? #include using names…
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 6What happens when you attempt to compile and run the following code? #include using names…
