Alex Rivera | Logout

Is it OK to use C-style cast for built-in types?

Asked 2009-02-09T12:43:53.077
19

After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?

Edit
Report

1 Answer

4

In my opinion C-Style casting of built in types when using standard library functions and STL is ok, and results in easier to read code.

In the company I work in we compile with maximum (level 4) warnings, so we get warnings about every little type cast etc... So I use c-style casts in these because they're small, not so verbose and make sense.

for (int i = 0; i < (int)myvec.size(); i++)
{
  // do something int-related with i
}
float val = (float)atof(input_string);

etc....

But if its on (eg library) code that may change, then static_cast<>() is better because you can ensure the compiler will error out if types change and the cast no longer makes sense. Also, its impossible to search for casts within code if you only use c-style. "static_cast<mytype>(" is pretty easy to search for. :)

answered 2010-06-29T23:28:57.280

Your Answer