How to convert C++ variables to other data types using casting

There are several ways to convert C++ variables.
Here is one method of converting an integer variable to a bool 
(boolean) variable:

int MyInteger = 0;
bool MyBool = (bool)MyInteger;

And here is another way:

int MyInteger = 0;
bool MyBool = static_cast<bool>(MyInteger);

In both cases, after the casting has been made, MyBool will contain the value false (since MyInteger was 0). If MyInteger was 1 or any other number different from 0, MyBool would’ve been true.

When you want to cast a int variable to an float variable, or a short variable to a long variable, or any other similar case, the casting can be done automatically, you don’t need to specify the data type the way we did with bool. In the example below we do automatic casting:

int MyInteger = 2005;
float MyFloat = MyInteger;

So simply assigning the integer variable to the float variable is enough.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top