C++ casting

Jun 28, 2013 at 3:00am
Hello people.
I know C++ treats something like int(5)/int(10)=0
To see the result 0.5 it's necessary do use static_cast<type>, is that right?
How can I use this, it's necessary to add any library?
I'll use this with arrays, the mechanism is the same?

thanks
Last edited on Jun 28, 2013 at 3:01am
Jun 28, 2013 at 3:30am
To do floating point division with integer parameters, you can do a simple C-style cast like this:
1
2
3
result = float(5)/10;
//or
result = double(5)/10;

which will give you 0.5. static_cast<> is the C++ version with minute differences, but in your case it hardly makes a difference.
1
2
3
result = float(5)/10;
//Is equivalent to
result = static_cast<float>(5)/10;

There is no need for any library to use static casts.

And yes, the same can be done with arrays. However, you should attempt to avoid any casts unless casting is really, really, really necessary and may be the only solution.
Jun 28, 2013 at 5:11am
In the case of literals, it's easier just to make the literal the correct type:

1
2
3
4
5
float result = 5.0f / 10 ;

// or 

double result = 5.0 / 10 ;
Last edited on Jun 28, 2013 at 5:12am
Jun 28, 2013 at 6:16pm
Thank you to the answers, helped a lot!
:)
Topic archived. No new replies allowed.