Copyright © Programs ++
Design by Dzignine
Friday, 20 January 2012

Type casting in C++

Type Casting in C++ is basically the explicit conversion of an operand to a specific data type. E.g. the conversion of int to float and vice-verse.
It is just a simple means of temporarily converting a variable from one data type to another without actually storing it.


for e.g if 'x' is an integer,say 5 and it is divided by 2 and the result i.e 2.5 would be stored as 2 not 2.5 because 5 is of int type so 5/2 would be computed and not 5.0/2. Hence the need for typecasting arises.
The following program demonstrates the above concept.


// Program to demonstrate type casting in C++
#include<iostream.h>

using namespace std:
int main()
{

    int x = 5;
    float result; // float variable to store the result
   
    result = x / 2; // divides 5 by 2 i.e 2.5 but only 2 will be stored as int is not typecasted
    cout<<" Result without typecasting int to float : "<<result;
    result = (float)x / 2; // divides 5 by 2 i.e. 2.5 which will be stored due to typecasting
    cout<<" \n Result when int is typecasted to float : "<<result;

    return 0;
} // end of main
   

   
   

0 comments:

Post a Comment

Comment Here....