Type Casting in C is used to convert a variable from one data type to another, and after type casting compiler treats the variable as the new data type. This tutorial will teach you how to type casting in C.



Syntax:

(type_name) expression

Without Type Casting

Example:

#include <stdio.h>
void main ()
{
    int a;
    a = 15/6;
    printf("%d",a);
}

Program Output:

In the above C program, 15/6 alone will produce integer value as 2.

c-before-type-casting

After Type Casting

#include <stdio.h>
void main ()
{
    float a;
    a = (float) 15/6;
    printf("%f",a);
}

Program Output:

After type cast is done before division to retain float value 2.500000.

c-after-type-casting

It's best practice to convert lower data types to higher data types to avoid data loss.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram