I'm a bit fuzzy on the basic ways in which programmers code differently in C and C++. One thing in particular is the usage of strings in C++ over char arrays, or vice versa. So, should I use strings or char arrays, in general, and why?
In C++ you should in almost all cases use std::string instead of a raw char array. std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.
So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.
C-strings are simply implemented as a char array which is terminated by a null character (aka 0 ). This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
Char arrays are mutable, Strings are not. Also, string is Array returns false, while char[] is Array returns true. Show activity on this post. No, it's not an array.
In C++ you should in almost all cases use std::string
instead of a raw char array.
std::string
manages the underlying memory for you, which is by itself a good enough reason to prefer it.
It also provides a much easier to use and more readable interface for common string operations, e.g. equality testing, concatenation, substring operations, searching, and iteration.
If you're modifying or returning the string, use std::string
. If not, accept your parameter as a const char*
unless you absolutely need the std::string
member functions. This makes your function usable not only with std::string::c_str()
but also string literals. Why make your caller pay the price of constructing a std::string
with heap storage just to pass in a literal?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With