C-Style Strings

C++ adds many useful features to its predecessor, C; in fact, C didn’t even have std::string! Instead, strings in C were represented as arrays of characters, and you’ll sometimes come across this type of string in C++ because they can take up a bit less memory.

Here’s how C-style strings can be used:

#include <iostream>

int main() {
    char name[] = {'M', 'a', 't', 't', '\0'};
    std::cout << name << "\n";
    return 0;
}

Program Ouput:

Matt

When creating C-style strings, the '\0' at the end of the array is required, as it indicates the end of the string. Therefore, the word “Matt” in a C-style string has a length of 5, not 4.

Here, I surround each character in the name array with single quotes because double quotes are used to surround strings. Sequences such as '\0', '\n', and more are considered single characters, so they can be surrounded by single quotes.

Shorthand

Creating C-style strings in the same way as in the program above is really tedious, so there’s a simpler way of doing the same thing:

#include <iostream>

int main() {
    char name[] = "Matt";
    std::cout << name << "\n";
    return 0;
}

Here, double quotes are used because “Matt” is a full string, not just a single character.

String Pointers

Because of the relationship between pointers and arrays, C-style strings can also be written like this:

#include <iostream>

int main() {
    const char *name = "Matt";
    std::cout << name << '\n';
    return 0;
}

However, not intuitively, a C-style string created as a pointer does not need to be dereferenced when printing the full string. Therefore, the program output for this example is “Matt“, not a memory address.

Also, anything in double quotes in C++ has the data type const char * (not char *) by default, so the data type used for the name variable above is declared as a const char *. Without doing this, a warning would be issued by the compiler:

C-Style Strings vs. std::string

Strings created the “C++ way” with std::string have access to many useful functions discussed earlier, such as insert, push_back, and size. Therefore, std::string is usually preferred over C-style strings.

However, because C-style strings don’t come with all the functions that std::strings have, they can take up less memory in your computer. If you don’t have a need for std::string‘s functions, using C-style strings may be the better choice.