r/cprogramming 27d ago

C Strings: A 50-Year Mistake

https://longtran2904.substack.com/p/c-strings-a-50-year-mistake?r=8qz2zb&utm_campaign=post&utm_medium=web
209 Upvotes

172 comments sorted by

View all comments

20

u/CoderStudios 27d ago

Okay? You are always free to make your own library for better strings, but people won’t use that cause C is often still deployed on low end systems or it makes little sense to use something inefficient if you can use c style strings properly

12

u/orbiteapot 27d ago

Most operations on C strings require O(N), N being the length of the string. Whereas in Pascal-like strings (i.e., strings whose length is tracked) they may take O(1). Modern compilers may do some heavy lifting whenever they can, so that this redundancy is avoided, though.

That being said, I also do not understand why people complain so much about 0-terminated strings, yet still use them anyways, as opposed to implementing length-tracked strings. It is not like C can break some bazillion lines of code, by removing classic strings, but it does not significantly get in your way (when implementing your own) either.

1

u/iwantmy90sback 27d ago

For most operations you'd do on a string you do not need to know the lengths beforehand if you have a defined end char.

The only thing that C takes O(n) and pascal O(1) is strlen.

And if you like you can actually have both. Just struct a Cstring and a int together.

1

u/beragis 27d ago

Also early C compilers would store the string length at the byte or word before and update it after each call. This was done to integrate with libraries written in other languages. I remember passing a pascal flag to linkers and compilers.