C Type Casting

In this tutorial, you will learn how to convert one data type to another using typecasting with the help of examples.


Typecasting means converting one data type to another. In C language, you can typecast data type one to another using the cast operator which is denoted by (type). For example, if you want to store an integer value into a float variable then you need to typecast ‘int’ to ‘float’.

Syntax

(type) expression

Note: It is always recommended to convert the lower value to higher to avoid data loss.

Example without typecasting

Let’s check an example where we will try to store an integer value into a float variable after dividing with another integer value.

#include <stdio.h>
int main()
{
    float f = 5 / 2;
    printf("f : %f\n", f);
    return 0;
}

Output

f : 2.000000

As you can see from the above example that c compiler does not typecast the value automatically before dividing. Hence, the output of the division is 2. Now the value 2 stores in the float variable and the C compiler automatically typecast it while storing the value.

Example with typecasting

Now we perform explicit typecasting using cast operator while dividing two integer values.

#include <stdio.h>
int main()
{
    float f = (float)5 / 2;
    printf("f : %f\n", f);
    return 0;
}

Output

f : 2.500000

In this case, the C compiler type cast integer values into float and then performs the division operation.

Please get connected & share!

Categories

Advertisement