Do pointers to string literals remain valid after a function returns?

后端 未结 4 506
温柔的废话
温柔的废话 2020-11-30 09:48

Is the pointer returned by the following function valid?

const char * bool2str( bool flg )
{
    return flg ? \"Yes\" : \"No\";
}

It works

4条回答
  •  [愿得一人]
    2020-11-30 10:44

    This code is valid and standard compliant.

    String literals are stored in read-only memory, and the function just gets the address of the chosen string.

    C++ standard (2.13.4) says :

    An ordinary string literal has type “array of n const char” and static storage duration

    They key to understand your problem here, is the static storage duration : string literals are allocated when your program launch, and last for the duration of the program. Your function just gets the address and returns it.

提交回复
热议问题