Open In App

Difference Between Null Strings and Empty String in C++

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, we generally initialize a string that does not store anything at declaration as either a null string or an empty string. They both may seem similar to each other but they are different in terms of what they store or refer to.

In this article, we will discuss the key differences between the null strings and empty strings in C++.

Null String in C++

A null string is a character pointer that points to the NULL. It means that it is not pointing to any memory location and does not refer to a valid string, and if we try to access or manipulate it, it will show undefined behavior. So we need to make proper checks and precautions when working with null pointers.

Syntax to Define Null String in C++

 char *str = NULL;

Example

The below example demonstrates that we cannot access a null string.

C++




// C++ program to demonstrate initialization of null string
  
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
    // Initializing null string
    char* str = NULL;
  
    // Attempting to access null string may lead to
    // undefined behavior
    cout << "First character: " << str[0] << endl;
    return 0;
}


Explanation: The above program leads to undefined behavior as we are trying to access null string which is not possible.

Empty String in C++

Initializing a string as an empty string initialing it with a string having no characters. In this case, the char pointer points to the valid memory address and stores a single ‘\0’ NULL character.

Syntax to Define Empty String in C++

string emptyStringName = "";

Example

The below example demonstrates the initialization of string as empty string.

C++




// C++ program to initialize an empty string and print it's
// size
  
#include <iostream>
#include <string.h>
  
using namespace std;
  
int main()
{
    // Initializing empty string
    string emptyStr = ""; // or string emptyStr;
  
    // Accessing empty string safely
    cout << "Empty String Size: " << emptyStr.size()
         << endl;
    return 0;
}


Output

Empty String Size: 0

Difference Between Null String and Empty String in C++

The key difference the we can expect when initializing string as null vs empty are given below:

Feature

Null String

Empty String

Initialization

Pointer initialized to NULL

String object created with no characters

Validity

Not a valid string.

Valid string object with zero characters.

Accessing data

May lead to undefined behavoiur if accessed.

Well-defined operations on an empty string.

Crash Risk

Higher risk due to potential null pointer.

Lower risk, due to operations on a valid object



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads