Question

What's going on here:

printf("result = %d\n", 1);
printf("result = %f\n", 1);

outputs:

result = 1
result = 0.000000

If I ensure the type of these variables before trying to print them, it works fine of course. Why is the second print statement not getting implicitly converted to 1.00000?

Was it helpful?

Solution

In the second case you have a mismatch between your format string and the argument type - the result is therefore undefined behavio(u)r.

OTHER TIPS

The reason the 1 is not converted to 1.0 is that printf is “just” a C function with a variable number of arguments, and only the first (required) argument has a specified type (const char *). Therefore the compiler “cannot” know that it should be converting the “extra” argument—it gets passed before printf actually reads the format string and determines that it should get a floating point number.

Now, admittedly your format string is a compile-time constant and therefore the compiler could make a special case out of printf and warn you about incorrect arguments (and, as others have mentioned, some compilers do this, at least if you ask them to). But in the general case it cannot know the specific formats used by arbitrary vararg functions, and it's also possible to construct the format string in complex ways (e.g. at runtime).

To conclude, if you wish to pass a specific type as a “variable” argument, you need to cast it.

An undefined behavior. An int is being treated as float

The short answer is that printf isn't really C++. Printf is a C function which takes a variable argument list, and applies the provided arguments to the format string basis the types specified in the format string.

If you want any sort of actual type checking, you should use streams and strings - the actual C++ alternatives to good old C-style printf.

Interesting, presumably it's fine if your put '1.0'

I suppose the printf only gets the address of the variable, it has no way of knowing what it was. But I would have thought the compiler would have the decency to warn you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top