I was revising some C concepts and tried this:
printf(\"%d %d %d\", \"%da\", \'a\', \'A\'); //16079992 97 65
I can understand that for a<
A string in C is a pointer, which has a numeric value (the address). So printf is just printing the address of the string there.
String literals in C are arrays of char which in this context will decay to a pointer to the first element.
What you have is undefined behavior though, since you are misspecifying the format string in printf
and telling it that the pointer is an int which it is not. Most compiler given the correct warning flags(which we should always be using) will provide a warning for this, for example gcc
provides the following warning when using -Wall
:
warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]
printf("%d %d %d", "%da", 'a', 'A');
^
clang
provides a similar warning it seems by default.
For reference, the draft C99 standard tells us a string literal is a array of char in section 6.4.5
String literals:
[...]initialize an array of static storage duration[...]For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence;[...]
decay to pointer is covered in section 6.3.2.1
Lvalues, arrays, and function designators:
[...]an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array[...]
and we get undefined behavior from section 7.19.6.1
The fprintf function:
[...]If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.