Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of type conversion:
- Implicit Type ConversionTake a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
Also known as ‘automatic type conversion’.
- Done by the compiler on its own, without any external trigger from the user.
- Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid loss of data.
- All the data types of the variables are upgraded to the data type of the variable with largest data type.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
- It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
x = 10;
// integer x
// character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
z = x + 1.0;
"x = %d, z = %f"
, x, z);
x = 107, z = 108.000000
- Explicit Type Conversion–
This process is also called type casting and it is user defined. Here the user can type cast the result to make it of a particular data type.
The syntax in C:
Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
x = 1.2;
// Explicit conversion from double to int
sum = (
)x + 1;
"sum = %d"
sum = 2
Advantages of Type Conversion
- This is done to take advantage of certain features of type hierarchies or type representations.
- It helps us to compute expressions containing variables of different data types.
This article is contributed by Ankita Dutta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above