In C, it is possible to convert data/value of one type to another. Suppose, a character variable(char) can be converted to an integer (We obtain ASCII value of the character in this way). Data type conversion can be done in two ways, implicitly by the compiler, or explicitly by the programmer.
Type Conversion/Promotion (Implicit)
If an expression contains operations of variables of different datatypes, then all the lower datatypes in the expression are converted to a common datatype, and the expression is then evaluated. Let us look at an example to understand the use of type promotion.
#include <stdio.h> int main() { int a = 20; char b = 'B'; // ASCII value of B is 66 float c = a + b; printf ("c is %f\n", c); return 0; }
The output produced is:
c is 86.000000
We are instructing to add an integer and a character and store the value into a float variable. The biggest datatype here is float, followed by integer. Therefore, character 'b' is promoted to an integer, and then to float. Integer 'a' is promoted to float, and then the final value (a + b) is stored as a floating type in the variable 'c'. Note that the integer value of a character gives the ASCII code of that character. The order of promotion is given below
int
can be promoted to
long
can be promoted to
long long
can be promoted to
float
can be promoted to
double
can be promoted to
long double
Type casting (Explicit)
Sometimes, A programmer might want to convert a datatype explicitly because the implicit type promotion is not enough or simply it has to be done to avoid logical errors.
A datatype can be forcibly converted to another datatype by the following syntax
(datatype) expression;
For example, consider the following code:
#include <stdio.h> int main() { int a = 20; int b = 6; float c = a/b; float d = (float)a/b; printf("Without Type casting %f\n", c); printf("With Type casting %f\n", d); return 0; }
The output :
Without Type casting 3.000000
With Type casting 3.333333
A binary operation on two integers will result an integer. so, division of two integers will result into an integer, causing the discarding of fractional part. Here, We've converted integer 'a' to float by typecast. Thus, the division is now between a float and an integer. Integer 'b' gets promoted to a float and the float result is stored into a float type variable. So, here is a combination of both type casting and type promotion. Thus, it is self explanatory why Type casting is important.
We've discussed Type promotion and Type casting. More tutorials to follow. Please comment below for any queries and suggestions.
Sign up here with your email
ConversionConversion EmoticonEmoticon