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

后端 未结 9 841
情书的邮戳
情书的邮戳 2020-12-01 16:09

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;

9条回答
  •  一生所求
    2020-12-01 17:00

    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. :)

提交回复
热议问题