问题
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