Can anyone explain me static casting? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
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;

18th Aug 2021, 3:00 PM
Elias Dayoub
Elias Dayoub - avatar
4 Respuestas
+ 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
18th Aug 2021, 3:23 PM
HK Lite
HK Lite - avatar
+ 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 >
18th Aug 2021, 3:23 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Along with static_cast, there's an another type of casting available in C++! It's the dynamic_cast. Learn about that too ;)
20th Aug 2021, 10:18 AM
Rishi
Rishi - avatar
0
Thanks... HK Lite & Madiha
18th Aug 2021, 3:30 PM
Elias Dayoub
Elias Dayoub - avatar