TYPE CAST OPERATOR
c++ permits type conversion of variable or expression using the type cast operator.traditional C cast are augmented in c++ by a function call notation as a syntactic alternative. The following two versions are equivalent.
(type-name)expression
type-name (expression)
|
Example
average=sum/(float)i;
average=sum/float(i);
|
A type-name behaves as if it is a function for converting values to a designated(target) type. The function call notation usually leads to simplest(simple) expressions. however, This can be used only when if the type is an identifier, for example
p= * (q);
is illegal. in such cases, we must use language C type notation.
p=( *)q;
|
alternatively we can use typedef to create an identifier of the required type and use it in the functional notation for example
typedef * int_pt;
p=int_pt(q);
ANSI C++ adds the following new cast operators
* const_cast
* static_cast
* dynamic_cast
* reinterpret_cast
using namespace std;
main() {
x = 26.09399;
y = 18.20;
z ;
z = (int) x;
cout << "Statement 1 - Value of (int)x is :" <
z = (int) y;
cout << "statement 2 - Value of (int)y is :" << z<< endl ;
return 0;
}
|
Statement 1 – Value of (int)x is :26
statement 2 – Value of (int)y is :18
|