×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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

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:

  1. long to int
  2. 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.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.