Extra zero char at end of string appears in C++ for range loop
"abc" is a
const char type: the final element is the NUL terminator (with value 0).
In the second snippet, the value of the NUL terminator is printed as the code is describing an iteration over that entire
const char array.
In the first snippet, the underlying iterator technology of the
std::string class sets the end iterator (which is not reached in the short form
for loop) to the NUL terminator. This behaviour is consistent with
In the first snippet you are iterating over a string using a range based loop. The
std::string type has
.end() iterators. The range based loop uses those to mark the beginning and the end of the range.
In the second snippet, you are using a range based loop to iterate over a string literal. A string literal is basically an array of characters that has an extra hidden
\0 character at the end. This character is convertible to integer value of
0. Hence the extra 0 in the output.