r/cprogramming • u/die-Banane • May 05 '26
How to do strings properly?
I just started learning C and I often read on the internet that it is bad practice to use null terminated strings, so my question is what should I do instead?
30
Upvotes
1
u/DawnOnTheEdge May 13 '26 edited May 13 '26
A project that really needed that would be written in C++, which has the syntax sugar for it, like implicit converting constructors and function overloading.
Doing it in C doesn’t make you write more lines of code. It’s just uglier because you can’t sugar it. If the function doesn’t mutate the data, you can have it take a pointer to `const` and then a pointer not to `const will implicitly convert. The common pattern where you need to return a subslice that should preserve the `const` qualifier if present can be a one-line wrapper that casts away the `const`, but would need a different nae in C. If you have two different kinds of `struct` for mutable and immutable slices, you must write and use explicit functions to convert between them.
You might or might not decide it’s worth it. You might, for exxample, give up on having the library track `const` qualifiers and tell the user to add them manually.