Explicit type conversion in C++ | Type casting in C++

Type Casting in C++

Explicit type conversion in C++ | Type casting in C++



Explicit type conversion in C++ | Type casting in C++

Explicit type conversion in C++ is also called  casting. We can use casting to convert output of an arithmetic expression into a specific data type .

Syntax

(Data_Type) Expression

Data_Type is any valid data type of C++.

Expression is a valid arithmetic expression of C++.

//Program to demonstrate Explicit conversion/Casting

#include<iostream> 
using namespace std;
int main()
{
float n;
n=10/3;             //Line 6
cout<<"\n10/3="<<n;
n=(float)10/3;           //Line8 
cout<<"\n10/3="<<n;
return(0);
}

Output:

c=3.333333

 In Line 6 of above program, values 10 and 3 are of int type so result of 10/3 should be of int type i.e. 3 .

** In Line 8 of above program, values 10 and 3 are of int type so result of 10/3 should be of int type i.e. 3  but due to casting by float i.e. (float)10/3  result will become 3.333333.

 



Spread the love
Lesson tags: explicit type conversion in c, Type casting in C++
Back to: C++ Programming Notes
Spread the love