Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing strings as null vs empty string

How would it matter if my C++ code (as shown below) has a string initialized as an empty string :

std::string myStr = "";
....some code to optionally populate 'myStr'...
if (myStr != "") {
    // do something
}

vs. no/null initialization:

std::string myStr;
....some code to optionally populate 'myStr'...
if (myStr != NULL) {
    // do something
}

Are there any best practices or gotchas around this?

like image 820
Saket Avatar asked Oct 07 '22 09:10

Saket


People also ask

Is it better to use NULL or empty string?

An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Are Strings initialized to NULL?

String Declaration Only See, member variables are initialized with a default value when the class is constructed, null in String's case.

IS NULL same as empty string in C?

They are different. A NULL string does not have any value it is an empty char array, that has not been assigned any value. An empty string has one element , the null character, '\0'. That's still a character, and the string has a length of zero, but it's not the same as a null string, which has no characters at all.

Is empty string same as NULL in JS?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


2 Answers

There's a function empty() ready for you in std::string:

std::string a;
if(a.empty())
{
    //do stuff. You will enter this block if the string is declared like this
}

or

std::string a;
if(!a.empty())
{
    //You will not enter this block now
}
a = "42";
if(!a.empty())
{
    //And now you will enter this block.
}
like image 81
SingerOfTheFall Avatar answered Oct 08 '22 21:10

SingerOfTheFall


There are no gotchas. The default construction of std::string is "". But you cannot compare a string to NULL. The closest you can get is to check whether the string is empty or not, using the std::string::empty method..

like image 29
juanchopanza Avatar answered Oct 08 '22 22:10

juanchopanza