CPA-21-02 practice question 32 of 35

What is the output of the program? #include #include using namespace std; int main () { string s1 = "Hello", s2 = "World"; s2 = s1 + s2; cout

Full set: 257 questions
Answer options
A: It prints: Hello
B: It prints: HelloWorld Correct answer
C: It prints: WorldHello
D: It prints: WorldHelloWorld
Correct Answer:
B. It prints: HelloWorld
Explanation

The C++ standard library overloads the + operator for std::string to perform string concatenation. In the program, s1 is initialized with "Hello" and s2 is initialized with "World". The expression s1 + s2 concatenates the contents of s1 and s2 in that exact order, resulting in the temporary string "HelloWorld". This new string is then assigned back to s2 using the assignment operator, overwriting its original value ("World"). Finally, cout << s2 prints the updated value of s2, which is "HelloWorld".

Why Incorrect

- Option A: "Hello" is the value of s1. The program prints s2, which has been updated to hold the concatenated string.
- Option C: The concatenation order is strictly left-to-right (s1 then s2), so "Hello" comes before "World".
- Option D: The assignment s2 = s1 + s2 replaces the old value of s2. It does not append the result to the existing "World" string.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 24.3.2.6 [string.op.plus], operator+ for basicstring.

- MIT OpenCourseWare, 6.096 Introduction to C++, Lecture 4: Strings and Streams.

Scroll to Top