int and float anomalities. Please Help !!

Pradeep.M's Avatar, Join Date: Feb 2012
Light Poster
Following is the programme:

int main()
int a=2;
float b=2.5;
printf("a: %d %f %d \n",a,a,a);
printf("b: %d %f %d \n",b,b,b);
printf("with f: %f with c:%c\n",150,150);
return 0;
OUTPUT( on gcc compiler)
a: 2 0.000000 148
b: 0 0.000000 1074003968
with f: 0.000000 with c:


the value 2 is printed correctly but 0 is printed with %f is used for int. No problem till here, but after this why 148 is printed. also, in the 2nd line, when %d is used for float variable , 0 is printed , no problem, but then why after that 0.000000 is printed even when %f is used for float...
in the end.. when I want to print the character corresponding to the ANSCI value 150 using %f.. 0 is printed and when using %c , nothing is printed

PLEASE clarify, with an example.
xpi0t0s's Avatar, Join Date: Aug 2004
Before the first printf, add the following line and show us the new complete output:
printf("sizeof(int)=%d; sizeof(float)=%d\n", sizeof(int), sizeof(float) );
But basically, this is because you're not using the correct format codes. Use %d for int AND NOTHING ELSE, and use %f for float AND NOTHING ELSE. They must match, otherwise you get undefined behaviour.