static_cast

This is a discussion on static_cast within the C++ Programming forums, part of the General Programming Boards category; Hi everyone can anyone clariy to me the use of static_cast with example. Why using it and where? thank you...

  1. #1
    yes
    yes is offline
    Registered User
    Join Date
    Jan 2006
    Posts
    32

    static_cast

    Hi everyone
    can anyone clariy to me the use of static_cast with example.
    Why using it and where?

    thank you

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,675
    Code:
    float fVal = 12.6f;
    int iVal = static_cast<int>(fVal);
    I used to be an adventurer like you... then I took an arrow to the knee.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Why using it and where?
    To announce to the reader of your code that a value is being converted to a different type. Sometimes, the compiler will implicity convert types for you:
    Code:
    double d = 10.7;
    int n = d;
    cout<<n<<endl;  //10
    But anyone who isn't aware that an automatic conversion is taking place might get confused. So, it is said to be good practice to make everything explicit by writing:
    Code:
    double d = 10.7;
    int n = static_cast<int>(d);
    cout<<n<<endl;  //10
    That ugly syntax punches the reader in the face to let them know n isn't going to equal 10.7.

  4. #4
    yes
    yes is offline
    Registered User
    Join Date
    Jan 2006
    Posts
    32
    Thank you so much, I fully understand it now.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21