Home »
C++ programming language
Differentiate widening and narrowing conversions with Examples in C++
Learn: What are the widening and narrowing conversions in C++? In this article we are going to differentiate both kinds of conversions with Examples.
Widening conversion
A "widening" conversion or typecast is a cast from one data type to another data type, where the "destination" data type has a larger range compare to the "source" data type.
For example:
- int to long
- float to double
Example of widening conversion
Consider the program:
#include <iostream>
using namespace std;
int main()
{
float F = 0.0F ;
int A = 10 ;
F = A;
cout<<"Value of F: "<<F<<endl;
return 0;
}
Output
Value of F: 10
In this conversion, there is no possibility of data lose.
Narrowing conversion
A "narrowing" conversion or typecast is the exact opposite of widening conversion.
For example:
- long to int
- double to float
Example of narrowing conversion
Consider the program:
#include <iostream>
using namespace std;
int main()
{
float F = 12.53F ;
int A = 0;
A = F;
cout<<"Value of A: "<<A<<endl;
return 0;
}
Output
Value of A: 12
In this conversion, there is possibility of data lose.