Reputation: 1481
Case 1:
printf("%f",(7/2));
in gcc output is 0.000000.
Case 2:
float k= 7/2;
printf("%f",k);
in gcc output is 3.000000.
In the first case printf expects float but gets Integer so gives wrong result. But in second case it does type conversion.
Here are my questions-
Upvotes: 2
Views: 393
Reputation: 106012
In 2nd case it is doing type conversion by default but why not in 1st case?
In the first case, 7
and 2
both are of int
type. Dividing 7
by 2
will give you an int
. Printing it with %f
will invoke undefined behavior. You will get anything. In this case there is no type conversion.
Try this
printf("%f", (7.0/2));
In the second case, k
is of float
type hence the result of 7/2
is converted to the type of k
by default.
Why does not gcc give type mismatch error/ warning in the first case?
Compiling the first statement with -Wall
flag is giving the warning:
[Warning] format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
Upvotes: 8
Reputation: 122383
GCC can give a warning, but you didn't enable it. Try compile with flag -Wall
, you would see:
warning: double format, different type arg (arg 2)
Upvotes: 4
Reputation: 11166
1) gcc does not by default check types in format string with arguments - so it "interpretes" the data (ie. the integer) as float at runtime
2) gcc now interpretes the float as float at runtime.
Upvotes: 2