1

I was reading the documentation of string::length and, as you can see, it says that

Returns the length of the string, in terms of bytes.

So my question is, is this ensured to be also the number of char that it contains?
I know that usually a char is 1 byte, but is this ensured somewhere? Like in the standard or somewhere else?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • The documentation states pretty clearly, *Returns the length of the string, in terms of bytes.*. If it is using multi-byte characters, it is still returning number of bytes, not number of characters. – lurker Jun 08 '20 at 11:23
  • 9
    I think [this `length` reference](https://en.cppreference.com/w/cpp/string/basic_string/size) have it much better worded: "Returns the number of `CharT` elements in the string," (a `char` doesn't have to be a "byte"). – Some programmer dude Jun 08 '20 at 11:23
  • To prevent solving an [XY problem](https://meta.stackexchange.com/q/66377/217657), let me ask: What is your real use case? – Melebius Jun 08 '20 at 11:27
  • btw `sizeof(char) == 1` by definition (not just "usually") – 463035818_is_not_an_ai Jun 08 '20 at 11:28
  • 2
    cplusplus.com is not an official reference. It's written by "enthusiasts", not experts, and is often confusing (and sometimes even wrong ). – molbdnilo Jun 08 '20 at 11:29
  • @Someprogrammerdude so, i can use string::length and be sure that it returns the number of chars, right? – Alberto Sinigaglia Jun 08 '20 at 11:35
  • It returns the number of *elements* that the string holds. One element might correspond to a single character, or it might be part of e.g. a multi-byte UTF-8 sequence. – Some programmer dude Jun 08 '20 at 11:50
  • @Someprogrammerdude I think you are misunderstanding the term “char” used by OP. It seems not to mean _character_ but “bytes (objects of type _char_)” as https://en.cppreference.com/w/cpp/string/basic_string/size defines it. – Melebius Jun 08 '20 at 12:31
  • @idclev463035818 and so why long sometimes on some architecture is 4 byte and in others 8? – Alberto Sinigaglia Jun 08 '20 at 20:18

0 Answers0