-
Basic C program help
Hello everyone,
IDE is Code::Blocks 10.05
When I compile the following
Code:
#include <stdio.h>
int main ()
{
int a = 30 ;
float b = 50.5 ;
printf ("%i + %f = %i", a, b, a + b) ;
getchar () ;
return 0 ;
}
I get 0 as the result. How is that possible? I read that you can use
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
i.e. 80
Please help
-
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.
Code:
printf(" %f \n", 3 ); // 3 is int. not promoted to float as format expects ....
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
-
Thanks guys that was quick and informative :)