Type casting in C is the process of converting one data type to another. This is useful when you need to manipulate or store data in different types, such as converting a float to an integer.
π There are two types of casting in C:
Implicit casting is performed by the compiler when converting smaller data types to larger data types, such as converting an integer to a float. This happens automatically without the need for explicit instructions.
int a = 5; float b = a; // Implicit conversion from int to float printf("%f", b); // Output: 5.000000
Explicit casting, or type casting, allows you to manually convert a data type to another. Itβs done using the syntax: (type_name)value
, where type_name
is the target data type.
double a = 3.14; int b = (int) a; // Explicit conversion from double to int printf("%d", b); // Output: 3
Hereβs how type casting works with various data types:
// Implicit casting char a = 'A'; // a = 65 (ASCII value) int b = a; // Implicit conversion from char to int float c = b; // Implicit conversion from int to float // Explicit casting float x = 5.6; int y = (int) x; // Explicit conversion from float to int printf("%d", y); // Output: 5
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!