I am using string in c++. And I am getting unusual answers sometimes if I don't initialize strings.
What is good practice don't initialize the string or If it has to be initialized What is the best way to do it?
If you are talking about std::string , you don't need to "initialize" it because it is automatically initialized to the empty string in its constructor. If you mean const char * or char * , then yes, you should initialize them because by default they point to garbage. Then you may consider remove it. As you wish.
Highlights: There are four methods of initializing a string in C: Assigning a string literal with size. Assigning a string literal without size. Assigning character by character with size.
To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).
String initialization can be done in two ways: Object Initialization. Direct Initialization.
If by "string", you mean char*
, then yes, they should be (even must be, or at least is it strongly recommended) initialized, like any other variable by the way.
If by "string", you mean std::string
, then they are initialized to empty string ("") automatically by default (default constructor).
std::string str;
std::cout << str; // will print nothing (empty string) for sure
char* str2;
std::cout << str2; // will most likely print garbage or even crash
The standard advice in c++ is always initialize all your variables. So yes, you should initialize it. That's just good practice.
When you say "unusual answers" we need more details to offer more advice.
If you are talking about std::string
, you don't need to "initialize" it because it is automatically initialized to the empty string in its constructor.
If you mean const char *
or char *
, then yes, you should initialize them because by default they point to garbage.
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