#include<stdio.h>
main()
{
int a = 66;
printf("%f", a);
}
It is printing 0.0000
as an answer, why?
And %f
is replaced with %c
it is printing B
. I am not getting the reason.
Please explain !!
#include<stdio.h>
main()
{
int a = 66;
printf("%f", a);
}
It is printing 0.0000
as an answer, why?
And %f
is replaced with %c
it is printing B
. I am not getting the reason.
Please explain !!
It is because your program invokes undefined behavior. You may get anything, either expected or unexpected.
If a conversion specification is invalid, the behavior is undefined.335) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
printf("%f",a);
^ %f specifier expects arguments of type float/ double.
And %f is replaced with %c it is printing B. I am not getting the reason
ASCII code of character B
is 66
. Using %c
specifier prints the (printable) character itself.
For printf()
:
[...] If any argument is not the type expected by the corresponding conversion specifier, or if there are less arguments than required by format, the behavior is undefined. If there are more arguments than required by format, the extraneous arguments are evaluated and ignored [...]
Although, for %c
, you correctly get the expected 'B'
(whose ASCII code is 66
), it is not recommended (imaging when you pass in 666
, which will get unexpected result as no ASCII code is 666
). At least, you should do type-casting beforehand:
printf("%f", (float)a);
printf("%c", (char)a);
Again, remember always use the corresponding specifiers for different types.
If you use %f specifier and do not provide a float number, but int, the behaviour is undefined. In practice the memory starting in the location where your int is will be interpreted as float number, so what gets printed depends on internal representation of ints and floats. For %c you got B since %c interprets your int as character code, and B's code is 66.
%f is used to print floating point number %c is used to print character %d is used to print integer number
so when you are using %c printf function converting from ascii value to character of B.
if you want to print the integer
printf("%d",a);
%c prints the character corresponding to 66 into ascii table. By default %f will print 5 digits after the decimal point, but you can change the behaviour with %.3f (for 3 digits)