是的,局部变量的生存期在创建它的范围内({
}
).
局部变量具有自动或本地存储.Automatic,因为一旦创建它们的范围结束,它们就会自动销毁.
然而,这里有一个字符串文本,它是在实现定义的只读内存中分配的.字符串文字不同于局部变量,它们在程序的整个生命周期中都是活动的.它们有static duration个[Ref 1]生命周期 .
A word of caution!
However, note that any attempt to modify the contents of an string literal is an undefined behavior (UB). User programs are not allowed to modify contents of a string literal.
Hence, it is always encouraged to use a const
while declaring a string literal.
const char*p = "string";
而不是
char*p = "string";
事实上,在C++中,声明不使用const
而不在C中声明字符串文字,但是,用const
声明字符串文字给了您编译器在您试图修改第二种情况下字符串字符串时的警告的优势.
100:
#include<string.h>
int main()
{
char *str1 = "string Literal";
const char *str2 = "string Literal";
char source[]="Sample string";
strcpy(str1,source); // No warning or error just Uundefined Behavior
strcpy(str2,source); // Compiler issues a warning
return 0;
}
Output:
cc1: warnings being treated as errors
prog.c: In function ‘main’:
prog.c:9: error: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type
请注意,编译器会针对第二种情况发出警告,但不会针对第一种情况发出警告.
要回答这里的几个用户提出的问题,请执行以下操作:
What is the deal with integral literals?
换句话说,以下代码有效吗?
int *foo()
{
return &(2);
}
答案是,不,这个代码无效.它的格式不正确,将导致编译器错误.
比如:
prog.c:3: error: lvalue required as unary ‘&’ operand
String literals are l-values, i.e: You can take the address of an string literal, but cannot change its contents.
However, any other literals (int
,float
,char
, etc.) are r-values (the C standard uses the term the value of an expression for these) and their address cannot be taken at all.
[Ref 1]C99 standard 6.4.5/5 "String Literals - Semantics":
在转换阶段7中,将值为零的字节或代码附加到由字符串文字或文字产生的每个多字节字符序列.The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence美元.对于字符串文字,数组元素具有char类型,并且使用多字节字符序列的单个字节进行初始化;对于宽字符串文字,数组元素具有wchar_t类型,并且使用宽字符序列进行初始化.
如果这些数组的元素具有适当的值,则这些数组是否是不同的,这一点尚不明确.If the program attempts to modify such an array, the behavior is undefined