Reputation: 5807
I looked over but couldn't find a decent answer.
I was wondering how printf works in case like this:
char arr[2] = {5,6};
printf ("%d%d",arr[0],arr[1]);
I was thinking that printf just walks through the format and when it encouter %d for example it reads 4 bytes from the it's current position... however that's gotta be misconcepition cause that above works perfectly.
so, where am I wrong ?
Upvotes: 6
Views: 4225
Reputation:
When you say:
printf ("%d%d",arr[0],arr[1]);
the string and the result of evaluating the two array expressions are placed on the stack and printf
is called. printf
takes the string from the stack and uses the % formatters in it to access the other stacked arguments in sequence. Exactly how it does that depends, as you say on the actual % value - for example, %d
reads 4 bytes but %f
reads 8 (for most 32-bit architectures).
Upvotes: 1
Reputation: 399703
You're right. But there's argument promotion that converts (among other things) your char
:s into int
:s when they are used with a "varargs" function like printf()
.
Upvotes: 9