Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...