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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.