-4

I have a legacy code snippet that looks like:

const char *GetStr() const {
  return ("");
}

I am wondering whether this is a risky code as instead of returning a global character pointer, returning a local string literal? For example, perhaps, the following code snippet is better.

const char *NullStr = "";
const char *GetStr() const {
  return NullStr; // instead of ""
}

What could be pros/cons?

Even the following implementation could be better:

const char *GetStr() const {
  static const char * lNullStr = "";
  return lNullStr;
}
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
  • 2
    Are you using C++ or C? – machine_1 Dec 19 '19 at 08:51
  • C++, but it's a part of legacy code, inherited – Dr. Debasish Jana Dec 19 '19 at 08:56
  • If you're really programming C++ (which I believe you do considering the `const` qualified function, don't tag C even for legacy C++ code) then you should not be using raw pointers for strings to begin with. The author of the function needs a smack on the head for writing it, in my not humble at all opinion. And with "modern" C++ there are alternatives for returning [optional](https://en.cppreference.com/w/cpp/utility/optional) data. Finally, if pointers are really needed, IMO the correct way to return "null" would be a null pointer. – Some programmer dude Dec 19 '19 at 08:56

1 Answers1

-1

Your first snippet is not strictly portable.

An alternative, which is, is:

const char *GetStr() const {
    static const char* s = "";
    return s;  
}

and also has the benefit that s is contained within the function.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483