Welcome, Guest. Please login or register. Did you miss your activation email?

Poll

This may not be directly related to SFML, but I was casting my int to a float for an SFML function. How would you suggest using typecasting.

Don't use typecasting, it's dangerous.
0 (0%)
Use typecasting minimally, it's risky.
0 (0%)
Only use typecasting when conversion types are less risky.
0 (0%)
Use type casting whenever it's fine.
0 (0%)
I don't know, lol.
1 (100%)

Total Members Voted: 1

Voting closed: December 26, 2022, 08:45:46 pm

Author Topic: Type casting in c++  (Read 724 times)

0 Members and 1 Guest are viewing this topic.

Sean Mulligan

  • Newbie
  • *
  • Posts: 16
    • View Profile
Type casting in c++
« on: November 28, 2022, 08:45:46 pm »
Thanks for your help. I have been coding in c++ for about a year, but I am unsure on more complex subjects.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10835
    • View Profile
    • development blog
    • Email
Re: Type casting in c++
« Reply #1 on: November 29, 2022, 03:01:07 pm »
Type casting can also be an indication of a flaw design or misunderstanding of a design.

For example, I've see a lot of SFML users cast mouse cursor positions (int) to world coordinates (float), because they want to compare/use the two. What those users don't realize is that the world coordinates can change at any moment, when the view is adjusted.
The solution instead should be to use the dedicated casting methods mapPixelToCoords or mapCoordsToPixel if you go the other way around.

Additionally, there's also sometimes a better way to "cast", by using explicitly defined constructors.

For example, if you want to cast two integers to a sf::Vector2f (where f stands for float), you could cast the two values to float, or you could construct a sf::Vector2i with the two integers and pass that to the sf::Vector2f constructor instead, which will then take care of the conversion.

Unless you use C-style casts (e.g. (int)2.5f) and stick to static_cast you won't really run into risky situations. The only thing that could go wrong, is that you lose precision.
When it comes to reintepret_cast or even worse dynamic_cast you have to be much more careful on what you do and when you use them.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Sean Mulligan

  • Newbie
  • *
  • Posts: 16
    • View Profile
Re: Type casting in c++
« Reply #2 on: November 30, 2022, 03:22:31 am »
Hey, thank you for replying. Your in-depth explanation of cating in sfml will really help me in future projects.