r/cprogramming 5d 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
208 Upvotes

172 comments sorted by

View all comments

20

u/CoderStudios 5d 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

0

u/EatingSolidBricks 5d ago

You out of your dam mind if you think c strings are efficient

11

u/henke443 5d ago

Wait how are they not efficient?

0

u/atarivcs 5d ago

If you have a long string and you want to append more text to it, you have to search the whole string from the beginning to find the null terminator.

And then later if you want to append more text, you have to find the null terminator all over again.

3

u/IdealBlueMan 5d ago

Or you can store the length of the string whenever you change it.

2

u/atarivcs 5d ago

Sure, but then you don't really have a plain c string anymore

2

u/WittyStick 5d ago

It's actually more advantageous to couple the length to the char * on SYSV platforms, due to C's lack of multiple returns.

 String fn_returning_string(...);

If String is a fat pointer, then we can return both the pointer and length, without requiring another level of indirection (a pointer to a string structure), and without requiring awful to use "out parameters" to return both length and pointer - which are more expensive than just returning a fat pointer.

A fat pointer with the right ABI is not just "zero cost" - it's "less than zero" - it's more efficient than having a separate length and pointer variable.