-1
#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 !!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208

5 Answers5

5

It is because your program invokes undefined behavior. You may get anything, either expected or unexpected.

C11: 7.29.2 Formatted wide character input/output functions:

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.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
3

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.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
2

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.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
1

%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);

java seeker
  • 1,246
  • 10
  • 13
0

%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)

Happy
  • 1,815
  • 2
  • 18
  • 33