Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a C++ string s, is s[s.size()] legal and always equal to '\0'?

Tags:

c++

string

If s[s.size()]=='\0', then it is convenient to treat it as a sentinel for some algorithm. I did a test and it's always equal to '\0', but some books says it's illegal to access s[s.size()].

like image 446
user4344026 Avatar asked Mar 06 '15 02:03

user4344026


People also ask

Why is a 0 necessary at the end of the string?

Note that \0 is needed because most of Standard C library functions operate on strings assuming they are \0 terminated. For example: While using printf() if you have an string which is not \0 terminated then printf() keeps writing characters to stdout until a \0 is encountered, in short it might even print garbage.

What is raw string in C++?

Raw String Literal in C++ A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ' \n, \t, or \” ' of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.

What does 0 mean with strings?

It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message.

How do you represent the end of a string in C++?

C++ String end() This function is used to return an iterator pointing to the last character of the string.


1 Answers

Yes, that will give a reference to a zero-valued character, as specified by the C++11 standard:

Requires: pos <= size().

Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.

where charT() is a value-constructed character, which will have the value zero. T is presumably a typo for charT. The C++14 draft (and presumably the final standard) says the same thing, with the typo fixed.

If you have a book that says otherwise, burn it or sell it to your enemies.

like image 197
Mike Seymour Avatar answered Sep 28 '22 08:09

Mike Seymour