Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string literal from an API

Tags:

c++

string

api

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?

like image 746
Marco A. Avatar asked Oct 03 '13 07:10

Marco A.


People also ask

Can you return a string literal?

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.

How do you declare a string literal?

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.

Can you return a string literal in C?

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.

Is char * A string literal?

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].


2 Answers

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."

like image 121
masoud Avatar answered Sep 27 '22 16:09

masoud


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.

like image 44
legends2k Avatar answered Sep 27 '22 17:09

legends2k