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;
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
" is pretty easy to search for. :)