[英]Are string literals automatically being casted to char* at compile time in C?
If I were to do something like: 如果我要做的事情如下:
printf("The string is: %s\n", "string1");
Is the following done at compile time: 以下是在编译时完成的:
printf("The string is: %s\n", (unsigned char*) "string1");
Or similar? 还是类似的?
It is defined by the standard that the type of string literals is an array of char
1 and arrays automatically decay to pointers, ie char*
. 标准定义了字符串文字的类型是
char
1的数组,并且数组自动衰减为指针,即char*
。 You don't need to cast it explicitly while passing it as an argument to printf
when %s
specifier is used. 当使用
%s
说明符时,将它作为参数传递给printf
时,不需要显式强制转换它。
Side note: In C++ it's const char*
2 . 旁注:在C ++中它是
const char*
2 。
[1] C99 6.4.5: "A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz"... an array of static storage duration and length just sufficient to contain the sequence . For character string literals, the array elements have type char
" [1] C99 6.4.5: “字符串文字是用双引号括起来的零个或多个多字节字符的序列,如”xyz“... 静态存储持续时间和长度的数组足以包含序列对于字符串文字,数组元素的类型为
char
“
[2] C++03 2.13.4 §1: "an ordinary string literal has type “array of n const char
” and static storage duration" [2] C ++ 032.13.4§1: “普通的字符串文字具有类型”n
const char
数组“和静态存储持续时间”
Your understanding is more or less correct, although the mechanism is different. 尽管机制不同,但您的理解或多或少是正确的。
Except when it is the operand of the sizeof
or unary &
operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" will be converted ("decay") to an expression of type "pointer to T
", and the value of the expression will be the address of the first element in the array. 除了当它是的操作数
sizeof
或一元&
运营商,或者是一个字符串被用来初始化一个声明另一个数组,类型“的N元件阵列的表达T
将被转换(“衰变”)”,以“指向T
指针”类型的表达式,表达式的值将是数组中第一个元素的地址。 This is true for all array types, not just string literals. 对于所有数组类型都是如此,而不仅仅是字符串文字。
The expression "string1"
has type "8-element array of char
" 1 ; 表达式
"string1"
具有类型“8-element array of char
” 1 ; in the printf
call it's not an operand of either the sizeof
or unary &
operators, nor is it being used to initialize another array, so it is implicitly converted to an expression of type "pointer to char
" 2 whose value is the address of the first character. 在
printf
调用中,它不是sizeof
或unary &
运算符的操作数,也不是用于初始化另一个数组,因此它被隐式转换为“指向char
指针” 2的表达式,其值是该地址的第一个角色。
const char
, so the expression will decay to type const char *
.
const char
数组,因此表达式将衰减为const char *
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.