Monday 29 January 2018

Typecasting

Typecasting

             Sometimes it is required to explicitly convert a variable from one data type to another. This concept is known as typecasting. Following program will make it clear.

--------------------------------------------------------------------------------------------------------------------------------



--------------------------------------------------------------------------------------------------------------------------------

Output : 

x = 2.000000
y = 2.333333
z = 2.000000

--------------------------------------------------------------------------------------------------------------------------------

             In the above program, both a and b are integers. Now, ( a / b ) = ( 7 / 3 )= 2 . Now, since x is a float type variable, so x stores 2.000000 . In case of y , variable a is converted to float and thus the expression is evaluated as
y = (float)a / b = ( 7.000000 / 3 ) = 2.333333. In case of z, the value of ( a / b ) is converted to float and the expression is evaluated as y = (float) ( a / b ) = float ( 7 / 3 ) = float ( 2 ) = 2.000000.

Implicit and Explicit Typecasting
 
             The example demonstrated above is an example of explicit typecasting in which we used a new data type in brackets before the variable name. We have converted a smaller data type ( int ) to a larger data type ( float ). We can also convert from larger to smaller data type if required. However, it leads to truncation and data loss. For e.g the expression int x = ( int ) 7.315672 would evaluate to x = 7.
There are cases in which compiler does automatic type conversion if variables of different data types are together used in an expression. This is known as implicit typecasting. In implicit type conversion, smaller data types are automatically converted to large data type. Following program will clarify this concept.
--------------------------------------------------------------------------------------------------------------------------------



--------------------------------------------------------------------------------------------------------------------------------

Output : 

z = 10.657231
w = 72
--------------------------------------------------------------------------------------------------------------------------------

We can observe that in the expression w = x + ch , ch is converted to an integer automatically since char is a smaller data type as compared to int and thus ascii value of A is added to x. Similarly, in the expression
z = x + y , x is implicitly converted to float data type by the compiler. 

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete