1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
pasha
  • 2,035
  • 20
  • 34

1 Answers1

4

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.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • 3
    _"not like "foo"s, which is an actual c++ string, which isn't null-terminated."_ - `std::string`s are NUL terminated (guaranteed since C++11 if I recall correctly, when `.data()` and `.c_str()` became functional equivalents). – Tony Delroy Nov 17 '20 at 19:20
  • 1
    @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. – Mooing Duck Nov 17 '20 at 19:26
  • 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 `NUL`s 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). – ShadowRanger Nov 17 '20 at 19:26
  • 1
    @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. – Lukas-T Nov 17 '20 at 19:26
  • 3
    @MooingDuck: Plain old C-style string literals are described as `NUL`-terminated too, and they [can have embedded `NUL`s in them](https://stackoverflow.com/q/34990187/364696). 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. – ShadowRanger Nov 17 '20 at 19:36
  • @churill "*in practice they don't append it just when calling `c_str`*" - prior to C++11, that was allowed, but no implementation actually did it. But since C++11, that is no longer possible. "*but always carry the terminator around*" - yes, that has generally the common case, even before C++11 required it. – Remy Lebeau Nov 17 '20 at 22:27