19.8.1. static_cast and const_cast

[ fromfile: types.xml id: staticcast ]

        static_cast<char>('A' + 1.0);
        static_cast<double>(static_cast<int>(y) + 1);
   

Example 19.10. src/ansicast/m2k.cpp

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin);
QTextStream cout(stdout);
QTextStream cerr(stderr);

const double  m2k = 1.609;    // conversion constant

inline double mi2km(int miles) {
    return (miles * m2k);
}

int main() {
    int  miles;
    double kilometers;
    cout << "Enter distance in miles: " << flush;
    cin >> miles ;  
    kilometers = mi2km(miles);
    cout << "This is approximately "
         <<  static_cast<int>(kilometers)
         << "km."<< endl;
    cout << "Without the cast, kilometers = "
         << kilometers << endl;
    double* dp = const_cast<double*>(&m2k); 
    cout << "m2k: " << m2k << endl;
    cout << "&m2k: " << &m2k << "  dp: " << dp << endl;
    cout << "*dp: " << *dp << endl;
    *dp = 1.892;  1
    cout << "Can we reach this statement? " << endl;
    return 0;
}

Output:

Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048  dp: 0x8049048
*dp: 1.609
Segmentation fault



1

What are we attempting to do here?


Casting away const

Example 19.11. src/casts/constcast1.cpp

#include <iostream>
using namespace std;

int main() {
    const int N = 22;
    int* pN = const_cast<int*>(&N);
    *pN = 33;
    cout << N << '\t' << &N << endl;
    cout << *pN << '\t' << pN << endl;
}
Output:

22      0xbf91cfa0
33      0xbf91cfa0