Hi everyone
can anyone clariy to me the use of static_cast with example.
Why using it and where?
thank you
Printable View
Hi everyone
can anyone clariy to me the use of static_cast with example.
Why using it and where?
thank you
Code:float fVal = 12.6f;
int iVal = static_cast<int>(fVal);
To announce to the reader of your code that a value is being converted to a different type. Sometimes, the compiler will implicity convert types for you:Quote:
Why using it and where?
But anyone who isn't aware that an automatic conversion is taking place might get confused. So, it is said to be good practice to make everything explicit by writing:Code:double d = 10.7;
int n = d;
cout<<n<<endl; //10
That ugly syntax punches the reader in the face to let them know n isn't going to equal 10.7.Code:double d = 10.7;
int n = static_cast<int>(d);
cout<<n<<endl; //10
Thank you so much, I fully understand it now.