In a c programming language, the data conversion is performed in two different methods as follows...
The type of the expression on right hand side and the type of the variable on the left-hand side of an assignment operator may not be same. In such a case, the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of assignment operator(=).
int a; float b; a=4.6; b=9;
from the above example-1 the value 4.6 cannot be stored in 'a' since it is an 'int'. In such a case, the float is demoted to an int and then its value is stored. Hence what get stored in i is 4.
Exactly opposite happens in the next statement. Here, 9 is promoted to 9.0 and then stored in b, since b being a float variable cannot hold anything except a float value.
float x,y,z; int a; a = x + 2 * y - z / 4 - 2.5;
from the above example-2 during evaluation of the expression, the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to a it is again demoted to an int and then stored in a
Arithmetic Instruction | Result | Arithmetic Instruction | Result |
k=5/2 | 2 | a=5/2 | 2.0 |
k=5.0/2 | 2 | a=5.0/2 | 2.5 |
k=5/2.0 | 2 | a=5/2.0 | 2.5 |
k=5.0/2.0 | 2 | a=5.0/2.0 | 2.5 |
k=2/5 | 0 | a=2/5 | 0.0 |
k=2.0/5 | 0 | a=2.0/5 | 0.400000 |
k=2/5.0 | 0 | a=2/5.0 | 0.400000 |
k=2.0/5.0 | 0 | a=2.0/5.0 | 0.400000 |
NOTE: The Type conversion (implicit type conversion) is automatically performed by the compiler
When compiler converts implicitly, there may be a data loss. In such a case, we convert the data from one data type to another data type using explicit type conversion known as Type Casting
To convert data from one type to another type we specify the target data type in parenthesis as a prefix to the data value that has to be converted. The general syntax of typecasting is as follows.
(datatype)datavalue or (datatype)variable
int a=5,b=2; float x; x=(float)a/b;
from the above example, When we evaluate 5 / 2 the result is a float value that is 2.5 but the result will be 2.0, To achieve accurate value we use type casting that is (float)a.
First value in a 5 is converted to 5.0 and then divide by 2 the result will be stored in x as 2.5