Thread: Casting

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    291

    Casting

    Just wondering like, is there any difference between
    Code:
        double d = 12.3456;
        cout << (int) d << endl;
    and
    Code:
        double d = 12.3456;
        cout << static_cast<int>(d) << endl;
    besides one is a hell of alot shorter to write ? static_cast<> is supposedly a c++ cast while () is more of a c-style cast but does it really matter. Tryed looking through the board but couldnt find any answers. Thanks for any input.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    I prefer the second style. The first is ambiguous -- it can mean any of three different kinds of casts, and which cast is done is up to the compiler to decide. The second is safer, it checks if that cast is legal.

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    I don't think there is a difference. It's just a style thing. It only really matters when you cast pointers to more derived classes.

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    There's no execution difference. But the static_cast is far easier to find if you're ever looking for casts in your source. Just load it in a text editor and search for [a-z]*_cast. If you're looking for a C-style cast you're going to have problems. () is just too common.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Casting
    By morvick in forum C++ Programming
    Replies: 2
    Last Post: 06-17-2007, 11:06 PM
  2. Casting Question (I think)
    By fayte in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 05:31 PM
  3. casting the system exstracted date into seperate ints
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 08-30-2005, 12:17 AM
  4. Type casting
    By Lionmane in forum C Programming
    Replies: 28
    Last Post: 08-20-2005, 02:16 PM
  5. question about casting pointers/other types also??
    By newbie02 in forum C++ Programming
    Replies: 3
    Last Post: 08-07-2003, 05:01 AM