Re:C Strings and my slow descent to madness
by junon on Thursday April 06, 2023 @09:47AM
(#35468257)
There is no "loose convention". A C string is a null terminated string of non-null bytes. That's the definition. Working with them in memory-unconstrained environments is unnecessarily hard.
[ Parent
| on HN ]
Re:C Strings and my slow descent to madness
by magicalhippo on Thursday April 06, 2023 @10:07AM
(#35468482)
There is indeed just convention. The language defines string constants similar to what you say[1] (an array of characters, terminated by a null character), but in the language itself there's no way to declare that a function takes a string rather than a pointer to a character. Alternatively if you work with a fixed-sized character array, there's nothing separating it from "just" an array of characters that are not null terminated.
So that strcmp expects a string rather than a pointer to a character is just convention. In languages which actually has strings as a concrete concept, like say Pascal and derivatives, you can actually differentiate between those two cases.
[1]: https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#...
Re:C Strings and my slow descent to madness
by int_19h on Thursday April 06, 2023 @03:47PM
(#35473423)
That means that the strings aren't properly reflected in the type system. But the existence of string literals with a very definite in-memory layout means that it's not just a convention even so.
Re:C Strings and my slow descent to madness
by magicalhippo on Thursday April 06, 2023 @03:50PM
(#35473467)
But you can't use those string literals in any way without relying on convention.
Re:C Strings and my slow descent to madness
by int_19h on Thursday April 06, 2023 @03:55PM
(#35473520)
That was my point. Although you can, actually - since literals themselves are array-typed, you can sizeof them to get the character count without relying on null termination. It's even possible to get a non-null-terminated literal if the target array type is not large enough to fit null, e.g.:
char s[3] = "foo"; // not null-terminated!
Re:C Strings and my slow descent to madness
by giantrobot on Thursday April 06, 2023 @05:36PM
(#35474851)
> character count
Byte count.
Re:C Strings and my slow descent to madness
by int_19h on Thursday April 06, 2023 @06:26PM
(#35475369)
If you want to be pedantic, "an object declared as type char is large enough to store any member of the basic execution character set". It doesn't actually have to be a byte.
In practice, in C context, character == char == byte. Other concepts have to use different names to avoid confusion with the language spec.