Why are the int and float passed in printf going to the wrong positions in the format string?

旧时模样 提交于 2019-12-25 09:29:21

问题


printf function int to %f , float to %d trying to experiment

#include<stdio.h>                                              
int main(){                                                    
    int i=10;                                                     
    float x=43.2892f;                                              
    printf("i=%f  x=%d \n",i,x);                               
    return 0;                                                  
}

OUTPUT:

i=43.289200  x=10      

Need help to understand why these variables are interchanging ?


回答1:


What you're doing invokes undefined behavior1, but looking at the resulting assembly using GCC on a platform with the System V AMD64 ABI we might formulate a hypothesis. The floating-point value is passed in the xmm0 register (an SSE register), while the integer is passed in the esi register (a general register). Presumably, your printf implementation expects floating-point numbers to be passed in SSE registers and integers to be passed in general registers, and simply picks the xmm0 register to read from when it encounters the first %f (and vice versa).


1Undefined behavior does not have to be "random" or "different every time". In this case the undefined behavior is quite consistent. Undefined behavior might even be exactly what you expected to happen; but it might also change when you upgrade your compiler.



来源:https://stackoverflow.com/questions/44571175/why-are-the-int-and-float-passed-in-printf-going-to-the-wrong-positions-in-the-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!