In this article, we are going to inspect three different ways of initializing strings in C++ and discuss differences between them.
1. Using char*
Here, str is basically a pointer to the (const)string literal.
char* str = "This is GeeksForGeeks";
- Only one pointer is required to refer to whole string. That shows this is memory efficient.
- No need to declare the size of string beforehand.
This is GeeksForGeeks GeeksForGeeks For Everyone
- This works fine in C but writing in this form is a bad idea in C++. That’s why compiler shows warning
of “deprecated conversion from string constant to ‘char*'” because in C string literals are arrays of char but
in C++ they are constant array of char. Therefore use const keyword before char*.
const char* str = "This is GeeksForGeeks";
- We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.
// CPP program to illustrate assigning
// *char value to other variable
// This initialization gives warning in C++.
// "deprecated conversion from string constant
// to 'char*'"
* str =
* str1 =
// No warning
// trying to modify const string literal
// gives Runtime error
cout << str << endl;
2. Using std::string
std::string str = "This is GeeksForGeeks";
Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type.
Note: Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.
When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.
Some of the useful std:string functions are discussed below.
5 5 HelloWorld HelloWorldGeeks true Hello HelloWorldForGeeks Found at Position:5 HelloGeeksForGeeks
Cases where you might prefer char* over std:string
- When dealing with lower level access like talking to the OS, but usually, if you’re passing the string to the
OS then std::string::c_str has it covered.
- Compatibility with old C code (although std::string’s c_str() method handles most of this).
- To conserve memory (std::string will likely have more overhead).
3. Using char
char str = "This is GeeksForGeeks"; or char str[size] = "This is GeeksForGeeks"; // Here str is a array of characters denoting the string.
- We can modify the string at later stage in program.