Home > Software design >  without pointer C string how to expression string is nullptr?
without pointer C string how to expression string is nullptr?

Time:09-27

On C string can expression two case :

1. string flag;                     /* empty string */
1. string flag = "Other content";   /* other string */

On Java String can expression three case :

1. String flag = NULL;              /* NULL */
2. String flag = "";                /* empty string */
2. String flag = "Other content";   /* other string */

On C can we expression the string as NULL (nullptr) ? if not use pointer .

My scene: I got string data from mysql , mysql expression way same as Java for string , NULL/empty/other .

My data model is used for Mysql And nlohmann Json .

CodePudding user response:

The answer below is quite theoretical.
In practice usually there's no real need to distinguish between an empty string and a null one and using std::string as is is the best solution. And if you only need to add only the "nullabilty" to your C string you can use std::optional as mentioned in the comments and other answer.


Having said that:

In Java a String is a reference type, meaning variables like flag actually hold a reference to the String object (and the reference can be null). An object can have multiple references to it, and when this number becomes zero the object can be automatically destroyed.

If you want to achieve an overall similar behavior in C , you can use std::shared_ptr holding a std::string:

#include <memory>
#include <string>
//...
std::shared_ptr<std::string> s1 = nullptr;      // null string
std::shared_ptr<std::string> s2 = std::make_shared<std::string>("");    // empty string
std::shared_ptr<std::string> s3 = std::make_shared<std::string>("abs"); // non empty string

CodePudding user response:

So you can use std::optional to express this:

std::optional<std::string> null_string = std::nullopt; // this is the "null" state

if (optional_string) { /// Can be used like a null or bool type

std::optional<std::string> empty_string = ""; // This is the empty string
std::optional<std::string> other_string = "Other content"; // The full string

Just be aware, that to use string interfaces, you will need to get the value of the string with .value() or operator*:

void print_string(const std::string& s);

print_string(*other_string);

This requires you to check that the string is actually valid before calling or you will invoke undefined behaviour.

  • Related