c programming printf format searches expressions

前端 未结 3 836
执念已碎
执念已碎 2021-01-24 22:40

I have a small question. I have this piece of code:

#include 

int main(){
    printf(\"%d, %f, %d\\n\", 0.9, 10, \'C\');
}

And

3条回答
  •  醉话见心
    2021-01-24 23:03

    It is undefined behaviour, so anything can happen.

    %d requires an int, but you are passing a double (not a float), so printf takes 4 bytes of the double value and interprets it as an int.

    %f requires a double, but you are passing an int. So it takes the 4 byte of the int and 4 bytes from the next memory and interprets it as a double.

    You are lucky to pass 16 bytes while printf expects 16 bytes, so the last value is the correct one.

提交回复
热议问题