The following code works:
int main(void)
{
float f = get_float();
int i = round(f*100);
printf("%i\n", i);
}
Yet, error generated if coding this way:
printf("%i\n", round(1.21*100));
Output says round(1.21*100)
is float
. So, then why
int i = round(f*100);
is fine?
When you do
int i = round(f*100);
you convert the result of the double
function round
. The converted result is stored in the int
variable i
, which can be used with the format "%i"
as it expects an int
argument.
When you pass the double
result of round
directly as an argument to a format that expects an int
you have mismatching format and argument types. That leads to undefined behavior.
No conversion is made in the call to printf
, and no conversion can be made since the code inside the printf
function doesn't know the actual type of the argument. All it knows is the format "%i"
. All possible type-information is lost for variable-argument functions.
This is because of the behavior of automatic type casting. In printf, automatic typecasting does not work. When you say %i, it simply expects integer, it can not convert double to integer and then print.
In assignment operation, double is converted to integer first and then it is assigned to left operand of the = operator. I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With