Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

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

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 
",i,x);                               
    return 0;                                                  
}

OUTPUT:

i=43.289200  x=10      

Need help to understand why these variables are interchanging ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


1 Undefined 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...