#include <stdio.h>
int main()
{
printf("%c code\n", 'C');
printf("%d", "");
return 0;
}
#include <stdio.h>
int main()
{
printf("%d", 3); /* result 3 */
printf("%d", '3'); /* result 51, because 3 is char (from ASCII table) */
printf("%d", ""); /
return 0;
}
I'm a beginner at C. I read "C Programming Absolute beginner's Guide" Thurd Edition by Greg Pery and Dean Miller. There are examples of %c %d and %f . I've started experiment with them and noticed thing that i can't explain how it was made. So i tried these examples with %d and understood how first two work. For last one i have ideas how computer read this but I ain't sure how all 0s and 1s combine together. If you have explanation of that, I will glad to response you back)))
Short answer is that it doesn't;
%d
expects its corresponding argument to be anint
, and a string literal is not anint
. The behavior is undefined, meaning that neither the compiler nor the runtime environment are required to handle the situation in any particular way. You'll get some kind of output (usually), just don't expect that output to be meaningful in any way.A string literal like
""
is an array expression; its type is "1-element array ofchar
". Under most circumstances, an array expression is converted, or "decays", to a pointer expression and the value of the pointer is the address of the first element of the array. So what you're actually passing toprintf
is achar *
value.You told
printf
to expect anint
, but you gave it achar *
. In practice, most implementations will attempt to interpret that pointer value as anint
and format it for display as a decimal integer.Problem is that on many modern implementations, a pointer value can't be represented in an
int
so only part of the value is converted and displayed. Some implementations may passint
arguments in specific registers rather than on the stack, soprintf
may not even be looking in the right place for the value and convert some random bit pattern.Again, the behavior is undefined so any result is equally "correct".