0
votes
#include <stdio.h>

int main(void) {
    char a[] = "125"; // (int)1, (int)2, (int)5. But array 'a' has a type char. So int is in char. ???
    printf("%s", a);
}

In that code, each element of string literal has type int. But the array a has type char.

In C99 6.4.5 $2 fragment
The same considerations apply to each element of the sequence in a character string literal or a wide string literal as if it were in an integer character constant or a wide character constant

In C99 6.4.5 $5 fragment
For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence

I think they are not compatible, it's a contradiction to me. What's wrong about my thought?

2
"Each element of string literal has type int." -- That is the part where you are wrong. A character literal has type int. A string literal has type char []. - DevSolar

2 Answers

2
votes

No, this is a string literal.

Quoting C11, chapter 6.4.5, String Literals:

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz".[...]

To elaborate, the acceptable syntax for a string liteal is:

string-literal:
                 encoding-prefixopt " s-char-sequenceopt "
          encoding-prefix:
                 u8
                 u
                 U
                 L
          s-char-sequence:
                 s-char
                 s-char-sequence s-char
          s-char:
                 any member of the source character set except
                              the double-quote ", backslash \, or new-line character
                 escape-sequence

and then, the "source character set", referring (Chapter 5.2.1/P3)

Both the basic source and basic execution character sets shall have the following members: the 26 uppercase letters of the Latin alphabet

         A   B   C   D   E   F   G   H   I   J   K   L   M
         N   O   P   Q   R   S   T   U   V   W   X   Y   Z
the 26 lowercase letters of the Latin alphabet
         a   b   c   d   e   f   g   h   i   j   k   l   m
         n   o   p   q   r   s   t   u   v   w   x   y   z
the 10 decimal digits
         0   1   2   3   4   5   6   7   8   9
the following 29 graphic characters
         !   "   #   %   &   '   (   )   *   +   ,   -   .   /   :
         ;   <   =   >   ?   [   \   ]   ^   _   {   |   }   ~

So, a construct like "123" is a string literal, not individual integers held by/in char.

1
votes
char a[] = "125"; 

In that code, each element of string literal has type int. But the array a has type char.

No, the fact that it's a 5 does not mean it has to be an int. The type of which has to be determined by the context of where/how it is declared.

In your case that 5 is of type char because it is part of the string literal.

Also note that 5 can be one of any other types such as unsigned int, unsigned short, double, etc. So again you must look at how it's declared in the first place.