Simple Question:
How do you return an empty C-String with as little code as possible?
I have code that needs to return an empty char*
. I am looking for something along the lines of return "";
. I know there are several ways to do this, but I am looking for the most efficient way possible.
Using return "";
gives warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
Thanks!
Short Answer:
const char *get_string() { return ""; }
or
char *get_string() { return const_cast<char *>(""); }
or
char *get_string() { return NULL; }
or
std::string get_string() { return std::string(); }
Detailed Answer:
Implicit conversion from string literal to char *
is supported in C and C++98/C++03, but apparently not in C++11. The deprecation warning is just there to let you know that this should be addressed, particularly if you want to be able to migrate your code C++11.
The empty string literal ("") is not actually empty, it is a string containing a single null character (\0). When you use return "";
, you are actually returning a pointer to the memory location of the const string literal so the function return type should be const char *
.
If you really must return a non-const pointer to a string literal, you can use the const_cast
operator to cast away the const
.
A better practice would be to return NULL (or nullptr
) for functions that are returning empty, non-const, C-style strings, but only if the calling code is checking for NULL pointers.
Note that C++ has its own string type (std::string
), and an even better practice would be to use this rather than a C-style string when possible.