Are string literals automatically being casted to char* at compile time in C?

坚强是说给别人听的谎言 提交于 2019-12-10 14:18:13

问题


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?


回答1:


It is defined by the standard that the type of string literals is an array of char1 and arrays automatically decay to pointers, i.e. char*. You don't need to cast it explicitly while passing it as an argument to printf when %s specifier is used.

Side note: In C++ it's 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"

[2] C++03 2.13.4 §1: "an ordinary string literal has type “array of n const char” and static storage duration"




回答2:


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. This is true for all array types, not just string literals.

The expression "string1" has type "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.


1. 7 letters plus the 0 terminator.
2. This is the case in C; in C++, string literals are arrays of const char, so the expression will decay to type const char *.

来源:https://stackoverflow.com/questions/19277609/are-string-literals-automatically-being-casted-to-char-at-compile-time-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!