C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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:

  1. int to long
  2. float to double

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:

  1. long to int
  2. double to float

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.









COMMENTS