I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway.
I can return something like std::string
:
std::string myFunction()
{
return "string";
}
or return const char*
:
const char* myFunction()
{
return "string";
}
Is the second alternative safe and portable in this scenario?
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
Character literals represents alphabets (both cases), numbers (0 to 9), special characters (@, ?, & etc.) and escape sequences like \n, \b etc. Whereas, the String literal represents objects of String class.
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.
Is the second alternative safe and portable in this scenario?
Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.
Yes! But beware of this potential gotcha:
char * myFunc() {
return "Constant string?";
}
Yes, you can convert a string literal to a non-const char *
! This will enable you to later break the world by trying to modify the contents of that char *
. This "feature" exists for legacy reasons -- string literals are older than const, and were originally defined as char *
in C.
g++ throws out an obnoxious warning for this, even in the default mode, thankfully. I don't know if VC++ throws out a warning just as eagerly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With