samairtimer samairtimer - 1 month ago 13
C++ Question

Why does the size of this std::string change, when characters are changed?

I have an issue in which the size of the string is effected with the presence of a

'\0'
character. I searched all over in SO and could not get the answer still.

Here is the snippet.

#include <iostream>
#include <string>



int main()
{
std::string a = "123123\0shai\0";
std::cout << a.length();
}


http://ideone.com/W6Bhfl

The output in this case is

6


Where as the same program with a different string having numerals instead of characters

#include <iostream>
#include <string>



int main()
{
std::string a = "123123\0123\0";
std::cout << a.length();
}


http://ideone.com/mtfS50

gives an output of

8


What exactly is happening under the hood? How does presence of a
'\0'
character change the behavior?

Answer

The sequence \012 when used in a string (or character) literal is an octal escape sequence. It's the octal number 12 which corresponds to the ASCII linefeed ('\n') character.

That means your second string is actually equal to "123123\n3\0" (plus another terminator).

It would have been very clear if you tried to print the contents of the string.

Octal sequences are one to three digits long, and the compiler will use as many digits as possible.