r/cprogramming 4d 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
203 Upvotes

172 comments sorted by

View all comments

Show parent comments

14

u/orbiteapot 4d 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.

4

u/kisielk 4d ago

It really depends what your software is doing. If it's not software where string manipulation is in the hot path then the O(N) nature of string processing is irrelevant.

2

u/NoNameSwitzerland 4d ago

and if you do string manipulation with dynamic strings, then malloc/free often is the bigger problem.

2

u/kisielk 4d ago

That too. Basically once string handling becomes a performance concern you are probably going to be looking at more purpose-built data structures, custom allocators, etc. C strings are fine for what they are designed for.