Type Casting in c
Type Casting in c
Type casting means changing a variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense.
For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.
Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.
Type conversion in c can be classified into the following two types:
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.
int x;
for(x=97; x<=122; x++)
{
printf("%c", x); /*Implicit casting from int to char thanks to %c*/
}
Explicit Type Conversion
The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable or expression.
For example,
int x;
for(x=97; x<=122; x++)
{
printf("%c", (char)x); /*Explicit casting from int to char*/
}
Rules for conversation
The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:
- All integer types to be converted to float.
- All float types to be converted to double.
- All character types to be converted to integer.
Example
Consider the following code:
int x=7, y=5 ;
float z;
z=x/y; /*Here the value of z is 1*/
If we want to get the exact value of 7/5 then we need explicit casting from int to float:
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is 1.4*/
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values to a common type. The compiler first performs integer promotion; if the operands still have different types, then they are converted to the type that appears highest in the following hierarchy −
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||.
Example:
#include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ float sum; sum = i + c; printf("Value of sum : %f\n", sum ); }
Output −
Value of sum : 116.000000