Type Casting in C or C++ Language

Type Casting in C++ Language

Type Casting:

The process by which converting data type of a value during execution, called TypeCasting. For example, if we have a float type variable and we need to use this variable as an integer variable. Here we need Type Casting. We can perform type casting in two ways:

  1. Implicit typecasting
  2. explicit typecasting
  • Implicit type casting:

Mostly C++ compilers have automated typecasting. It’s mean that compiler automatically converts one data type to another data type. In implicit typecasting, a user cannot able to decide the data type in which he/she wants to convert. The compiler decides the data type. After automated conversion, the compiler gives a warning. The warning is the conversion from ‘long’ to ‘int’, possible loss of data.

If an expression is a mixed-type expression then the answer of this expression calculated to the larger data type in the expression. Typecasting order is as follows:

type casting

Here, double is the highest data type and a byte is the lowest data type. Some examples of implicit conversions are as follows:

Expressions

Answer

Int + double

Double

Float * int

Float

Int / long

long

Program:

#include<iostream.h>

using namespace std;

int main(){

int a;

double b=12;

a = ++b;

cout<<“value of a is: “<<a;

return 0;

}

Try It Now:

  • Explicit typecasting:

Explicit casting is done by the programmer. A programmer can perform it by using a cast operator. The cast operator tells the compiler to change a data type of variable. The syntax of cast operator is:

(dataType) expression

In the above syntax, dataType shows that data type in which we want to change a variable. And expression is constant, variable or an expression whose data type is to be changed.

Program:

#include<iostream.h>

using namespace std;

int main(){

int a=12;

double b;

b = (double) ++a;

cout<<“value of b is: “<<b;

return 0;

}

Try It Now:

You can also read about Data Types (Built-in vs User-defined Data Types) and we have also the collection of other topics of the C++ course. Also, like our facebook page

Summary
Review Date
Reviewed Item
Type Casting in C or C++ Language
Author Rating
51star1star1star1star1star

Add a Comment

Your email address will not be published. Required fields are marked *