gpt4 book ai didi

c - (字符串)文字的范围

转载 作者:太空狗 更新时间:2023-10-29 16:22:59 25 4
gpt4 key购买 nike

我总是尽量避免返回字符串文字,因为我担心它们不是在函数外定义的。但我不确定是否是这种情况。让我们以这个函数为例:


const char *
return_a_string(void)
{
return "blah";
}

这是正确的代码吗?它确实对我有用,但也许它只对我的编译器 (gcc) 有用。所以问题是,(字符串)文字是否有一个范围,或者它们是否一直存在/定义。

最佳答案

此代码适用于所有平台。该字符串作为静态字符串文字被编译到二进制文件中。例如,如果你在 Windows 上,你甚至可以用记事本打开你的 .exe 并搜索字符串本身。

因为它是一个静态字符串文字范围并不重要。

字符串池:

需要注意的一件事是,在某些情况下,可以“合并”相同的字符串文字以节省可执行文件中的空间。在这种情况下,每个相同的字符串文字都可以具有相同的内存地址。但是,您永远不应该假设情况会或不会。

在大多数编译器中,您可以设置是否对 stirng 文字使用静态字符串池。

字符串文字的最大大小:

一些编译器对字符串文字有最大长度限制。例如,对于 VC++,这大约是 2,048 字节。

修改字符串文字会产生未定义的行为:

永远不要修改字符串文字。它有一个未定义的行为。

char * sz = "this is a test";
sz[0] = 'T'; //<--- undefined results

宽字符串文字:

以上所有内容同样适用于宽字符串文字。

例子:L"这是一个宽字符串字面量";

C++ 标准声明:(lex.string 部分)

1 A string literal is a sequence of characters (as defined in lex.ccon) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type "array of n const char" and static storage duration (basic.stc), where n is the size of the string as defined below, and is initialized with the given characters. A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type "array of n const wchar_t" and has static storage duration, where n is the size of the string as defined below, and is initialized with the given charac- ters.

2 Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

关于c - (字符串)文字的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/267114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com