Type casting in C++


Type casting in C++


Sometimes we required to force the compiler to explicitly convert the value of an expression
to a particular type.This would be clear from the below example :


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

void main()
{
float a;
int x=6;
int y=4;

a=x/y;

cout << "\nValue of a= "<< a;

getch();
}

The output will be :

Value of a=1

The answer is 1 and not 1.5. This is because x and y both are integer and hence
6/4 yields an integer=1.

Solutions to this problem are:

1. Change the type int to float of any of the x or y variable or

2. Typecasting


Tpecasting :

Following example shows how to do typecasting :

void main()
{
float a;
int x=6;
int y=4;

a=(float)x/y;

cout << "\nValue of a =" << a;
}

Noe the output will be :

Value of a =1.5

This program used typecasting in which we put float in paranthesis before the evaluating expression.

a=(float)x/y;

The expression (float) causes the variable x converted to type float from type int before
being used in division operation.

This was the concept of type casting.




     Prev                                                   NEXT

0 comments:

Post a Comment