3

I know that a string literal is always null terminated, even "" has a length of 1.

Is it the same case with raw string literal, ex: does R"()" has a length of 1?

3
  • 1
    You can std::cout << sizeof(R"()") << '\n'; to see for yourself ;-). Commented Nov 17, 2020 at 19:19
  • 2
    Or check it in the reference: en.cppreference.com/w/cpp/language/string_literal Commented Nov 17, 2020 at 19:19
  • Thanks TonyDelroy, churill Commented Nov 17, 2020 at 19:23

1 Answer 1

5

Raw string literals are just normal C strings that ignore escapes, which means they're still null-terminated. It's not like "foo"s, which is an actual c++ std::string, which isn't necessarily null-terminated.

Sign up to request clarification or add additional context in comments.

6 Comments

"not like "foo"s, which is an actual c++ string, which isn't null-terminated." - std::strings are NUL terminated (guaranteed since C++11 if I recall correctly, when .data() and .c_str() became functional equivalents).
@TonyDelroy It's a little tricky. "Null terminated" usually means two things: "theres a 0 byte at the end, and that there's no 0 byte anywhere else, so the end of the string can be found by searching for a null. AKA: The null terminates the string" std::string has a 0 byte at the end, but can also contain 0s throughout, so the assumption that you can find the end by searching for 0 doesn't hold. Definitions get a little wobbly here.
You may be thinking of "foo"sv, which, being a std::string_view, isn't required to be NUL-terminated. "foo"s is guaranteed to store a NUL after the last character (it could have NULs earlier on, so as Mooing Duck notes, it's not "terminated" when you see a NUL, but it's guaranteed to have at least one at the end).
@t.niese Right, I guess, in practice they don't append it just when calling c_str, but always carry the terminator around. But yes, basically that answer is correct.
@MooingDuck: Plain old C-style string literals are described as NUL-terminated too, and they can have embedded NULs in them. Sure, C-string oriented APIs won't see anything past the first embedded NUL, so it's fairly useless normally, but that doesn't mean the literal can't contain them. C++ strings know their size, so the terminal NUL doesn't exist to define where they terminate, but they always terminate with a NUL. Point is,std::string is NUL-terminated just like C string literals.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.