Home » Type Casting Operator In C++

Type Casting Operator In C++1 min read

by Abu Zar Mishwani
Implicit and Explicit Type Casting In C++

Type Casting Operator:

Type casting is the process of converting data from one type to another. When a variable is type cast to a new data type, the compiler treats it as a new data type. There are two kinds of Type Casting Operators available in C++.

  • Implicit type casting
  • Explicit type casting

Implicit Type Casting:

When data is used in expressions, the compiler automatically changes it from one type to another via implicit type casting. The compiler implicitly changes a value of one type to the value of the new type when it is assigned to another type.

For Example:

int x = 3.14156;	//implicit casting to integer value 3
// Program Example: Implicit Type Casting

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	
	int x = 3.14156;
	cout<< " Type Will Implicitly Change Here: "<< x;
	
	return 0;
}

OUTPUT OF THE PROGRAM:

Type Will Implicitly Change Here: 3

Explicit Type Casting:

Explicit conversion of explicit type casting occurs when a user manually changes data from one type to another. 

There are various ways to convert one type to another in C++, but the easiest is to use the new type enclosed in parentheses ( ) before the expression to be converted.

For Example:

// Program Example: Explicit Type Casting

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	
	int x;
    float pi = 3.14;
	x = (int) pi;	//changing the type explicitly
	
	cout << " Type Will Explicitly Change Here: "<<x;

	
	return 0;
}

OUTPUT OF THE PROGRAM:

Type Will Explicitly Change Here: 3

In the above code, the float number 3.14 is converted to an integer value 3, and the remainder (.14) is discarded. Here, the type casting operator is (int).

Leave a Comment

Related Articles

Send this to a friend