Unexpected output of printf

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.

Leave a Comment