Thread: Newbie cast question

  1. #1
    Registered User
    Join Date
    Jul 2009

    Newbie cast question

    Hi all,

    I have recently started to teach myself to program with C++ and have a question concerning casts.

    What is the difference between -

    i = sqrt(static_cast<double>(n))

    and -

    i = sqrt((double) n)

    Many thanks,


  2. #2
    Registered User
    Join Date
    Mar 2007
    Google knows all

    First hit should give you your answer.

  3. #3
    Registered User
    Join Date
    Jul 2009
    Sorry, I still don't understand. Can someone spell it out for me?

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    They are, in this particular use, the same. One is C++ style, the other is C style, but the result is the same.

    However, the C++ style cast family is more specific than the C style casts, and this allows better checking of various conditions where in C you can do really stupid things, in C++ the compiler tells you "that's not right".

    It is also easier (if you understand the C++ style casts) to see what is actually being done and whether it is (for example) a portable cast, or if it's going to potentially cause problems when porting to another architecture. For example
    char * p = (char *)x;
    doesn't really tell you much of what is done with x.

    On the other hand
    char *p = reinterpret_cats<char *>(x);
    is more clearly saying "we have some other type than char * in x". And it's very easy to search for reinterpret_cast, whilst a (char *) cast is quite dificult to find - particularly you want to find the other casts that translate to (int *) or (mystruct *).

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Jul 2009
    Aha! I suspected as much. I tried substituting each type in a program and they seemed to do the same thing. Many thanks for your patience and the explanation.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie function return question
    By faifas in forum C Programming
    Replies: 2
    Last Post: 06-29-2009, 10:19 AM
  2. Stupid Newbie question
    By TimL in forum C++ Programming
    Replies: 4
    Last Post: 07-22-2008, 04:43 AM
  3. Newbie with Very Newbie Question
    By Jedi_Mediator in forum C++ Programming
    Replies: 18
    Last Post: 07-01-2008, 08:00 AM
  4. newbie: array question :(
    By cstudent in forum C Programming
    Replies: 2
    Last Post: 04-09-2008, 06:46 AM
  5. Replies: 28
    Last Post: 07-16-2006, 11:35 PM