sherrellbc
sherrellbc

Reputation: 4853

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?

Upvotes: 5

Views: 194

Answers (2)

John Bode
John Bode

Reputation: 123548

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 *.

Upvotes: 4

LihO
LihO

Reputation: 42103

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"

Upvotes: 12

Related Questions