Type Casting
The process of converting a value from one data type to another during arithmetic operation is called casting or type casting.
Types of Casting
There are two types of type casting;
i) Explicit Casting
ii) Implicit Casting
i) Explicit Casting
The word "explicit" means 'open' or 'clean'. In explicit casting, the data type in which the value is to be converted is clearly specified in the program. It is done by cast operator. The cast operator is unary operator. It converts the value of an expression in the value of the type specified.
The general form of the cast operator is;
( type ) expression
Where
type It indicated one of the C data type (or a user-defined data type) to which the value of the expression is to be converted.
expression It indicated the constant value, variable or an expression whose data type is to be converted.
For example, to convert a floating-point value 3.156 into an integer value, the statements are written as;
int x ;
x = ( int ) 3.156 ;
printf ( " %d " , x ) ;
After executing the above statements, the floating-point value will be converted into integer. The value is assigned to variable 'x'. The decimal portion will be truncated. The value 3 will be displayed on the screen.
ii) Implicit Casting
The word "implicit" means 'understood' or 'embedded'. In implicit casting, the data type in which the value is to be converted is not specified in the program. It is automatically done by the C-compiler.
When constant values and variables of different types are mixed in an expression, they are converted into the same type. The compiler will convert all operands of lower order data type into higher order data type. The order of data types is given in the following table.
Data Type
|
Order
|
long double
|
Highest
|
double
|
|
float
|
|
long
|
|
int
|
|
short
|
|
char
|
Lowest
|
In the above table, 'long double' data type has the highest order while 'char' data type has the lower order. For example, if an expression has highest order operand data type 'int' then all 'char' and 'short int' will be converted into 'int'.
Similarly, in the assignment statement when the value of one data type is assigned to a variable of another data type. The type of the value being assigned is converted into the data type of variable to the left side of assignment operator. For example;
int x ;
float y = 49.723 ;
x = y ;
The data type of the variable 'x' is 'int'. When the value of 'y' is assigned to 'x', it is converted into integer type. The value 49 will be assigned to 'x'. The decimal portion of 'y' will be truncated.
No comments:
Post a Comment
Thanks For Visiting Here...!! I will Reply you as soon as possible.