Thread: static_cast

  1. #1
    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,817
    Code:
    float fVal = 12.6f;
    int iVal = static_cast<int>(fVal);
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    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
    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