CPA-21-02 practice question 8 of 35

What is the output of the program? #include #include using namespace std; int main() { char str[] = "Hello\0\World\0"; cout

Full set: 257 questions
Answer options
A: It prints: Hello Correct answer
B: It prints: World
C: It prints: HW
D: It prints: World\0World
Correct Answer:
A. It prints: Hello
Explanation

In C++, string literals are arrays of constant characters. When the operator<< of std::ostream is used with a const char (a C-style string), it prints characters sequentially until it encounters the first null-terminator character (\0). In the array "Hello\0\World\0", the first null character appears immediately after "Hello". The output stream stops reading at this exact point, ignoring the rest of the array's contents. Thus, it prints "Hello".

Why Incorrect

B. Incorrect because the stream stops at the first null terminator, which occurs before "World" is reached.
C. Incorrect because the entire word "Hello" is processed before the stream encounters the null terminator.
D. Incorrect because the stream does not ignore null terminators; it strictly stops at the first one it encounters.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 30.7.5.2.4 [ostream.inserters.character], Paragraph 4: Character inserters output characters until a null character is reached.

2. Stanford University, CS106L Standard C++ Programming, Streams and I/O documentation.

Scroll to Top