What is a narrowing conversion?
Posted by Daisy WilliamsNov 30
A narrowing conversion is an explicit type conversion or casting. It is used when the destination data type is narrower than the source data type, an explicit type conversion is required. The general form of this explicit conversion is given below:
(target-type) value
Here, target-type is the desired data type and value is the value to be converted.
For example:
int num1, int num2;
short num3;
num3= (short)(num1+num2);
In the example above, the sum of two 32-bit integer data type variables num1 and num2 is assigned to another variable num3, which is of integer type short (16-bit). Therefore, an explicit conversion takes place before assigning the value to num3. Otherwise, if this explicit type conversion is not performed, and the sum of variables num1 and num2 is directly assigned to variable num3, a compile-time error will be generated.
No comments