Reputation: 3668
I've never bothered to look for printf as I started learning C++ without C. Now i want to use formatted output in some project. so I'm looking for some references that can explain the difference between using printf and IO streams.
One of my doubt are:
float f = 1.5;
printf("%d", f);
Why does it print zero? FWIK it should be reinterpreting float as int is that true?
Upvotes: 2
Views: 205
Reputation: 839194
When you write printf("%d", f);
the type of f
must be int. The code as you have written it invokes undefined behaviour. Taken from an answer to a similar question:
in the documentation for fprintf (7.19.6.1/9) which also applies to printf, it explicitly states that if any argument is not the correct type for the format specifier - for an unmodified %d, that is int - then the behaviour is not defined.
Why does it print zero?
Maybe they ran out of nasal demons?
Upvotes: 4
Reputation: 95
if you don't want to use %d format specifier ,then you better Type cast it Explicitly to avoid UB(Undefined Behavior ) to be called.
float f=1.5; printf("%d",(int)f);
Upvotes: 0
Reputation: 361802
It actually invokes undefined behavior (UB). If the format specifier doesn't match with the type of the argument passed to printf
, then it is UB, which means anything could happen. It can print 0
, or 9878978
or any garbage. Anything, entirely unpredictable, could happen.
Use %f
if the data type of the argument is float
.
Upvotes: 7
Reputation: 1625
Yes you already have the answer, %d
will print integer values only. Use "%f
" which stands for float values . If you use %f
you will get 1.500000
Upvotes: 0
Reputation: 882716
Because %d
is for printing integers, not floats. You need one of the floating point format strings, like %f
.
The usual conversions between data types don't work here because printf
is a varargs-type function where you can basically push whatever you want onto the stack (or equivalent if your implementation is not stack-based) and, if it doesn't match what's in your format string, all bets are off - it's undefined behaviour.
See here for one of the things that can go wrong when you have such a mismatch.
Upvotes: 2