I'm writing a user API, is it right to return a const char* value this way?
const char * returnErrorString(int errorCode)
{
switch(errorCode)
...
return "This error code means that...";
}
I don't like returning string literals this way but they shouldn't be destroyed before being read by the user due to RVO optimizations, is this correct? Any suggestion on that?
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.
The best way to declare a string literal in your code is to use array notation, like this: char string[] = "I am some sort of interesting string. \n"; This type of declaration is 100 percent okey-doke.
It's perfectly valid to return a pointer to a string literal from a function, as a string literal exists throughout the entire execution of the program, just as a static or a global variable would.
String literals are convertible and assignable to non-const char* or wchar_t* in order to be compatible with C, where string literals are of types char[N] and wchar_t[N].
It's OK.
String literal has a fixed address during program's life. You can pass its address as pointers to everywhere. String literals will not destroy while the program is alive.
Just try not to modify them which invokes undefined behavior. Per § 2.14.5 : "The effect of attempting to modify a string literal is undefined."
String literals are const
; they're put up in the read-only data segment (GCC puts it in .rodata section); some implementations store them in the text/code segment, which too is read-only. This is one of the reasons it's illegal to modify a string literal this way.
char *literal = "You can't edit me!"; // compiler will flag it as a warning for missing const
literal[0] = 'U';
Don't worry about its destruction; it will live as long as the process/application which uses your library/API is active.
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