0
Can anyone explain me static casting?
I learnt about changing variables types using static casting...I didn't get it right...can anybody tell me how compiler works with this example: int x{7}; x=static_casting <int>{3.12}; x=static_casting <double>{5.12}; cout<<x;
4 Réponses
+ 2
static cast is the safest type of type casting as I know.
The keyword is static_cast instead of static_casting
int x;
x=static_cast<int>(3.12);// converting 3.12 to integer type
cout<<"I am x: "<<x<<endl;
// if you want to use the value of the variable to convert then
int j= 56.2;
j=static_cast<int>(j);
cout<<"I am j: "<<j<<endl;
x=static_cast<double>(5.12); // converting to double
cout<<"Second x: "<<x<<endl; // but because of x's type as int it still again gets converted to int
double y;
y= static_cast<double>(5.12);
cout<<"I am y: "<<y<<endl; // double outputs 5.12
For more explanation https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx
+ 1
When you defining any variables like float x=3.2344 something whatever you want . Here i have defined one variable x and am assigning double value to float variable here x type is float but 3.2.... is double value. Becz By default floating points number treat as double type.
But when you type casting from
Short to int data type
Int to float
float to double ..
Here when we type casting lower data type to higher then higher data type able to store value but in case of
double to float
Or float to int here we casting Higher data type to lower data type and your data will lose some precision. In this case we using
static_cast<your data type >
+ 1
Along with static_cast, there's an another type of casting available in C++! It's the dynamic_cast. Learn about that too ;)