When static_cast should be used?

Discussion in 'C++' started by PengYu.UT@gmail.com, Jun 4, 2005.

  1. Guest

    , Jun 4, 2005
    #1
    1. Advertising

  2. Joe Gottman Guest

    <> wrote in message
    news:...
    > Hi,
    >
    > An example usage of static_cast is at
    > http://publib.boulder.ibm.com/infoc...oc/language/ref/clrc05keyword_static_cast.htm
    >
    > But I don't understand why it is necessary to use
    > float d = static_cast<float>(j)/v;
    >
    > Isn't
    > float d = float(j)/v;
    > enough?
    >



    It isn't strictly necessary. float d = float(j)/v works. But there are
    several reasons why you should use the various *_cast operators
    1) It makes clear exactly what you are doing. static_cast forces
    implicit conversions (int to float for instance) which is why you use it in
    your example. const_cast casts away constness. reinterpret_cast makes the
    computer pretend that a variable of one type is actually of another type.
    dynamic_cast is used for run-time type identification; it checks whether a
    pointer to a base type is actually a pointer to the target derived type then
    returns the cast pointer if it is or 0 if it is not. A plain C cast can
    replace any of these except dynamic_cast, but it is helpful to you and
    anyone who will have to maintain your code later to be specific about what
    you are doing.

    2) It is much easier, both for humans and computers, to search for
    static_cast in code than to look through all the parentheses to try to
    determine which are casts.

    Joe Gottman
     
    Joe Gottman, Jun 5, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chandra Shekhar Kumar

    static_cast confusion

    Chandra Shekhar Kumar, Jun 24, 2003, in forum: C++
    Replies:
    7
    Views:
    2,019
    Mirek Fidler
    Jun 27, 2003
  2. Wenjie
    Replies:
    4
    Views:
    417
    Victor Bazarov
    Jul 12, 2003
  3. alg

    static_cast<>

    alg, Jul 14, 2003, in forum: C++
    Replies:
    2
    Views:
    496
  4. Bo Peng
    Replies:
    11
    Views:
    1,091
    Victor Bazarov
    Oct 20, 2006
  5. junyangzou
    Replies:
    13
    Views:
    258
Loading...

Share This Page