GDNet community manager Washu has written about the perils of C-style strings for beginners (in C++). In his post, he covered a variety of excellent points, but he missed one of my favorites: C-style strings are not a type.
A C-style string is just an interpretation of an actual type (a char*) that adds some additional semantics. These semantics are not enforced by the language, except implicitly and very poorly via some C library functions. This approach, which presumably grew out of the “pay for what you use” mentality, is a huge part of what makes C-style strings cumbersome and error-prone.
Tags: c++, for-beginners
Agreed.
When C was created, the C string implementation was optimized for memory/CPU constraints, not ease of use; it made some sense back then. But C-style strings should never have been called “strings”; they are, as you mentioned, merely arrays of characters. (Perhaps there was some “type envy” back then, “Look, we have strings too!”; after all Pascal had a proper string type . . .)
I’m a little boggled that we continue to use C-style strings as strings, and even teach them as a valid “type”. The std::string is superior in so many ways — we need to all just use that and relegate C-style strings to the “ancient times” when we didn’t have anything better.
And while we’re at it, let’s stop teaching/using this mixed C/C++ garbage; pick C, or pick C++. People say learning C++ is hard; I say learning C++ is actually pretty straight-forward. What’s difficult is trying to learn the C/C++ mix that so many books espouse.