The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. ― Donald E. Knuth

# C Tutorial

## 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.

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.

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.