简体   繁体   中英

How does printf work?

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 ?

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM