C Programming
In this tutorial we will learn about type conversion in C programming language.
In C we can have expressions consisting of constants and variables of different data types.
There are two type of conversions in C.
C performs automatic conversions of type in order to evaluate the expression. This is called implicit type conversion.
For example, if we have an integer data type value and a double data type value in an expression then C will automatically convert integer type value to double in order to evaluate the expression.
Following are the rules for the implicit type conversion in C.
First, all char and short are converted to int data type.
char
short
int
Then,
long double
double
float
unsigned long int
long int
unsigned int
Remember the following hierarchy ladder of implicit type conversion.
If we downgrade from a higher data type to a lower data type then it causes lose of bits.
For example: Moving from double to float causes rounding of digits.
Downgrading from float to int causes truncation of the fractional part.
In explicit type conversion we decide what type we want to convert the expression.
Syntax of explicit type conversion is:
(type) expression
Where, type is any of the type we want to convert the expression into.
In the following example we are converting floating point numbers into integer.
#include <stdio.h> int main(void) { //variables float x = 24.5, y = 7.2; //converting float to int int result = (int) x / (int) y; //output printf("Result = %d\n", result); printf("End of code\n"); return 0; }
Output
Result = 3 End of code
In the above code (int) x converts the value 24.5 into 24 and (int) y converts the value 7.2 into 7 so, we get 24/7 i.e., 3 as result because result is of type int and hence the decimal part is truncated.
(int) x
(int) y
result