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

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.

#include <stdio.h>

int main() {
    int a = 7, b = 3;
    float x, y, z;
    x = a / b;          /* x = 2.000000 */
    y = (float)a / b;   /* variable 'a' is typecasted [ y = 2.333333 ] */
    z = (float)(a / b); /* (a / b) is typecasted [ z = 2.000000 ] */
    printf("x = %f\ny = %f\nz = %f\n", x, y, z);
    return 0;
}

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.

#include <stdio.h>

int main() {
   int x = 7, w;
   float y = 3.657231, z;
   char ch = 'A'; /* ascii value of 'A' is 65 */
   w = x + ch;    /* ch is implicitly converted to int type */
   z = x + y;     /* x is implicitly converted to float type */
   printf("z = %f\n", z); /* z = 7.000000 + 3.657231 */
   printf("w = %d\n", w); /* w = 7 + 65 */
   return 0;
}

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.

Back | Next