Evorlor
Evorlor

Reputation: 7553

Return an empty C-String

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!

Upvotes: 3

Views: 15734

Answers (2)

Chris Olsen
Chris Olsen

Reputation: 3511

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.

Upvotes: 10

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

char* foo()
{
    static char empty[1];
    return empty;
}

Just be aware that this function is absolutely stupid, and whatever your actual problem is, this is not likely the correct solution. But, since you refuse to expound upon your actual problem, here you go.

Upvotes: 2

Related Questions