Introduction
In our C programs, an expression may contain data
values of different data types. When the expression contains values of similar type
values then no conversion is required. But if the expression contains values of
different types then they must be converted to desired type. In a c programming language, the data conversion is
performed in two different methods as follows:
(i).Type
Conversion
(ii).Type
Casting
- In this procedure, a data value from one data type to another data type is converted automatically by the compiler.
- Also known as implicit type conversion.
- The implicit type conversion is automatically performed by the compiler.
- To evaluate the
expression, the data type is promoted from lower to higher level where the
hierarchy of data types can be given as: double, float, long,
int, short, and char.
#include<stdio.h>
int main(){
int x=3,u;
float y,v=4.59;
y= x;
u=v;
printf("y=%f\n",y);
printf("u=%d\n",u);
return 0;
}
Output:
y=3.000000
u=4 //data loss
- also called as explicit type conversion or forced conversion.
- Implicit type conversion may lead to data loss as in above example. That’s why we need type casting.
- To convert data from one type to another type we specify the target data type in paranthesis as a prefix to the data value that has to be converted.
- Type casting can be done by placing the destination data type in parentheses followed by the variable name that has to be converted.
(data/Type) variableName
Example:
#include<stdio.h>
int main(){
int x=3;
float y;
y= (float)x;
printf("y=%f\n",y);
return 0;
}
Output:
Y=3.000000
No comments:
Post a Comment