Type Conversion in Assignments
It happens when type of the expression on RHS and variable on LHS of the assignment operator (=) are not of the same type.
Rule - value of the expression is promoted or demoted depending upon the type of the variable on LHS of the = (assignment).
e.g.
int a ;
flaot b;
a = 3.5 ;
b = 30 ;
In instruction third a=3.5 value on RHS (3.5) is float. It can't be stored in varible a as it is int. Therefore in this case value of float 3.5 is demoted to int and then it is stored in the variable.
Hence value 3 is stored in the variable a.
b = 30 ;
As b is float therefore value on RHS is promoted to float type (30.000000) and then it is stored in the varibale b.
Statement | Result | Statement | Result |
---|---|---|---|
x = 2 / 9 | 0 | y = 2 / 9 | 0.000000 |
x = 2.0 / 9 | 0 | y = 2.0 / 9 | 0.222222 |
x = 2/ 9.0 | 0 | y = 2 / 9.0 | 0.222222 |
x = 2.0/9.0 | 0 | y = 2.0 / 9.0 | 0.222222 |
x = 9/2 | 4 | y = 9 / 2 | 4.000000 |
x = 9.0/2 | 4 | y = 9.0 / 2 | 4.500000 |
x = 9 / 2.0 | 4 | y = 9 / 2.0 | 4.500000 |
x = 9.0 / 2.0 | 4 | y = 9.0 / 2.0 | 4.500000 |
Last modified: Wednesday, 17 November 2021, 3:14 PM