C Type Casting

Type Casting in C is used to convert a variable from one data type to another data type, and after type casting compiler treats the variable as of the new data type.Syntax:

(type_name) expression

Without Type Casting

Example:

#include <stdio.h>
void main ()
{
    int a;
    a = 15/6;
    printf("%d",a);
}
In the above C program, 15/6 alone will produce integer value as 2.

After Type Casting

#include <stdio.h>
void main ()
{
    float a;
    a = (float) 15/6;
    printf("%f",a);
}
After type cast is done before division to retain float value 2.500000.

It’s best practice to convert lower data type to higher data type to avoid data loss.

Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *