std::char_t...ts::length,(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::char_traits::length πŸ’–

okay so welcome to the std::char_traits::length page from the C++ Standard Libary manual β€” yes, that’s the manual name right up top, and we are absolutely doing this. This one is short, cute, and very β€œjust read the null terminator, bestie.”


πŸŽ€ NAME πŸŽ€

The NAME situation is truly a choice, and it shows up literally like this:

std::char_traits::length,std::char_traits::length, -
       std::char_traits::length,std::char_traits::length,

Anyway: this page is about std::char_traits::length, and yes, it’s giving β€œthe same thing said twice with commas.” Iconic in a chaotic way.


πŸ¦‹ Synopsis πŸ¦‹

Here’s the signature moment, literally:

std::char_traits<char32_t>::length

static std::size_t length( const char_type* s );  (constexpr since C++17)

So it returns the length of the character sequence pointed to by s, which is the position of the terminating null character (char_type()). No cap.

Also, for the general requirements on character traits for X::length, see CharTraits. That’s right there in the original, so don’t come for me.


🌸 Parameters 🌸

  • s β€” pointer to a character sequence; this is the sequence whose length you’re getting back. That’s the whole assignment, bestie.

πŸ’… Return value πŸ’…

The length of the character sequence pointed to by s. Periodt.


✨ Complexity ✨

Linear. No sneaky shortcuts, no magical constant-time glow-up. Just linear, fr fr.


πŸ“ Example πŸ“

Run this code and watch it do its lil thing:

// Run this code

#include <iomanip>
#include <iostream>
#include <string>

void print(const char* str)
{
    std::cout << std::quoted(str) << " has length = "
              << std::char_traits<char>::length(str) << '\n';
}

int main()
{
    print("foo");

    std::string s{"booo"};
    print(s.c_str());
}

🌈 Output 🌈

"foo" has length = 3
"booo" has length = 4

Source/version: http://cppreference.com, dated 2024.06.10, page tag std::char_t...ts::length,(3). byeee, go count your characters responsibly πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from