Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to initialize a string in c++? [closed]

Tags:

c++

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?

like image 750
Varun Teja Avatar asked May 03 '16 09:05

Varun Teja


People also ask

Is it necessary to initialize string?

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.

Can you initialize a string in C?

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.

Which is the correct way of initialising a string variable?

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).

What are two ways to initialize a string?

String initialization can be done in two ways: Object Initialization. Direct Initialization.


3 Answers

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
like image 193
jpo38 Avatar answered Oct 25 '22 01:10

jpo38


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.

like image 27
johnbakers Avatar answered Oct 25 '22 01:10

johnbakers


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.

like image 1
Minas Mina Avatar answered Oct 24 '22 23:10

Minas Mina