static casts??

Hey guys..

Can someone please explain what static_cast<datatype>(2)Does?..
And why can't I just divide by a normal integer or double over that?
A static_cast converts to expression inside the parentheses to the datatype inside the brackets. You may be seeing it used in division to force floating point division in some cases.

If you are having trouble with code that is using it, you could post the snippet and we could try to explain what's wrong.
I'm just lookin through my textbook and the piece of code is(which is inside a double function):
Radius =diameter/static_cast<double>(2);

Since radius is a double variable already, do I have to convert the 2 inside parenthesis, is there a difference?

And is the code above different from just convertin the two in implicit form.
Like double(2)? Or ..
/2.00;
i think that it depends on diameter variable. If it is either int or double.

If diameter is an int then lets say:
double radius = 2/3;
2/3 should result in 0,6666666666666667 but since both these number are int it would be rounded down to 0. Then int 0 would be assigned to double radius.
Last edited on
Oh every variable declared is a double type
then that static_cast is just a matter of precaution
Rather than write

static_cast<double>(2)

or

double radius = static_cast<double>(2)/static_cast<double>(3);

you should write

2.0

and

double radius = 2.0/3.0;

The .0 tells the compiler that it's a double literal rather than a signed integer (some lazy people don't bother with the 0, but I think that's less readable, esp. when scanning code fast.)

Andy

PS This recent thread might be semi-relevant?

What is a suffix and when is it used
http://www.cplusplus.com/forum/beginner/106449/
Last edited on
Topic archived. No new replies allowed.