Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra zero char at end of string appears in C++ for range loop

The following code

#include <iostream>
#include <string>
int main()
{
    std::string s = "abc";
    for (char c : s)
        std::cout << (int) c << " ";
}

prints "97 98 99 ".

The following code

#include <iostream>
int main()
{
    for (char c : "abc")
        std::cout << (int) c << " ";
}

prints "97 98 99 0 ".

Where is the extra 0 coming from in the second code?

like image 629
Albatossable Avatar asked Jun 22 '20 16:06

Albatossable


People also ask

Do Strings end with 0?

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

What is the meaning of \0 in string?

'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing. In C language it is generally used to mark an end of a string.

What is the mean of \0 in C++?

The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end. So following will be valid representation of strings in C.

How do I get all the letters in a string in C++?

string at() in C++std::string::at can be used to extract characters by characters from a given string. Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0).


1 Answers

The literal "abc" is a const char[4] 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[4] 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 s.size().

like image 121
Bathsheba Avatar answered Sep 22 '22 09:09

Bathsheba