Why use casting instead of just declaring the correct data type from the start?

Sorry for the dumb question...I'm learning about casting right now (doesn't seem too bad at all, to be honest). I'm wondering why you would need to use casting when you could just declare your variable with the correct data type from the start (i.e. just call your variable, "double mNumber," instead of "int mNumber").



Thanks.
Last edited on
You are exactly right.

The use of casting should be minimized, and you should prefer to just use the correct type from the start.

Casting is a fallback for when you have to use a certain type for one reason, but then need to send it to some other code which uses a different type. But largely you want to avoid that as much as possible.
@leo255
I'm wondering why you would need to use casting when you could just declare your variable with the correct data type from the start


Even if you will declare a variable with "a correct type" this in general case does not allow to escape casting because you need use expressions in your program that can have types different from the type of your variable.

Consider for example the following code snip

1
2
3
4
5
6
7
enum Color { Black, Red, Green, Blue, Magenta, Yellow, Whate, Total };

for (  Color c = Black; c != Total; c = static_cast<Color>( c + 1 ) )
{
   std::cout << c << ' ';
}
std::cout << std::endl;


It is a simplified example and if to substitute Color c for int c in the loop the casting will not be required. However in the general case there mignt be no such a possibility and you wiil need to use the casting.
Last edited on
Topic archived. No new replies allowed.