Basic C program help
IDE is Code::Blocks 10.05
When I compile the following
I get 0 as the result. How is that possible? I read that you can use
int main ()
int a = 30 ;
float b = 50.5 ;
printf ("%i + %f = %i", a, b, a + b) ;
getchar () ;
return 0 ;
expression instead of variables in the arguments which is what I did
exactly. If I add one more variable for eg. int result = a + b
and then instead of a+b i write result then I get the desired output
Because a+b is a float, it gets passed to printf as a floating-point value (specifically a double, by the magic of automatic promotion in function calls). But you told printf that it was an integer, so it grabs four bytes (instead of the eight that was probably given as a double) and interprets it as an int; and the four bytes it grabbed apparently was all 0.
Variadic function like printf() cannot help promote its argument.
This is wrong.
Now consider what's the type of a + b. a is int. b is float. Result of (a+b) type is float. see The C Book — Expressions and arithmetic
printf(" %f \n", 3 ); // 3 is int. not promoted to float as format expects ....
Thanks guys that was quick and informative :)