Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data type confusion in C

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?

like image 502
juanli Avatar asked Jul 19 '17 08:07

juanli


2 Answers

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.

like image 198
Some programmer dude Avatar answered Oct 06 '22 12:10

Some programmer dude


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.

like image 31
Darshan Prajapati Avatar answered Oct 06 '22 12:10

Darshan Prajapati