Is it necessary to initialize a string in c++?

Is it necessary to initialize a string in c++?

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. Thats just good practice.

When you say unusual answers we need more details to offer more advice.

Is it necessary to initialize a string in c++?

If you are talking about std::string, you dont 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.

Leave a Reply

Your email address will not be published. Required fields are marked *