Hi everyone
can anyone clariy to me the use of static_cast with example.
Why using it and where?
thank you
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);
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
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: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.