Type Conversions in Expressions in C

C expressions may contain many variables and constants which may be having different data types. However, when they are evaluated they should be raised or grounded to same common type for the sake of correct evaluation. Certain automatic type conversions are done by C compiler. In general, a narrower operand is converted into a wider one without losing information if expression involves a wider variable or constant. Consider the example below,

int x = 10;
float y = 5.5;
double z;
z = x + y;

In this example, integer variable x will be first converted to float (temporarily) and then the contents will added to real variable y. The result will be raised to double that will be assigned to z. However, x will still be an integer and y will still be a floating point. It should be noted that if z would have be integer type, then the result would have been grounded to integer.

Sometimes, due the complexity of an expression and nature of computation required, explicit type conversions are needed. Consider an example below

int x = 10, y = 3;
float z;
z = x / y;

Because both x and y are integers, the fractional part will be dropped during division. However, because z is floating point variable, the result (3) will be raised to float (3.000). In explicit type conversions, any variable or constant can be forced for a type conversion that is different from automatic conversion. In order to achieve this, C language provides type-casting operator which takes first argument as the data type to which the second argument should be type casted temporarily. The general syntax of type casting is as follows

( data-type ) Expression;

So using explicit type casting, we can solve the above mentioned problem as shown below.

In this case, x is type-casted to float. Thus, to evaluate the expression y is also raised to float. Hence, the result is accurate and is assigned to z.