Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 883
sherrellbc Avatar asked Oct 09 '13 16:10

sherrellbc


1 Answers

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"

like image 67
LihO Avatar answered Sep 27 '22 22:09

LihO