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
310 views
in Technique[技术] by (71.8m points)

c - Unexpected output of printf

int a=5;
float b=3.5;
printf("%d",b);
printf("
%f",a);

Can anyone please tell me why this code is showing unexpected output (garbage 3.5)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You are passing a float for the %d format string, but printf is expecting an int.

printf is a variable argument list function: printf(const char *format_string,...);

This means that the rest of the arguments after the format string can be of any type and number, and the compiler doesn't know what they should be. It is up to the programmer to provide arguments that are of the type that printf is expecting. What printf expects is determined by the format string. When you give a %d in your format string, the printf function is going to expect that the next argument is an int. Since you are passing a float, something strange is probably going to happen. For example, those bytes which make up the floating point number might be treated as if they were an int, which won't give you any meaningful value.

Actually it is a little more complicated than that. There are special rules about how parameters are passed to variable argument functions. One of the rules is that float values are passed as doubles. Which means that your float value is first converted to a double before being passed to printf. Most likely a double is eight bytes on your platform, while an int is only four. So the printf function could be treating the first four bytes of your double value as an int.

What is perhaps even worse is that on the next line, an int is being passed where a double is expected. Which means that the printf function could treat the first four bytes of your int as part of the double, and then read four more bytes that weren't even part of your arguments.

The details of what actually happens is platform-specific. The language simply states that you shouldn't pass the wrong type of arguments and makes no guarantees about will happen if you do.


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

...