ch3-ConstCast in C/C++
Chapter_3 Exercise_3-14 StaticCast | ReinterpretCast Exercise_3-15 |
ConstCast TCP1, p. 184 (constcast.c, ConstCast.cpp)
constcast.c download
int main()
{
const int i = 0;
int* j = (int*)&i;
long* l = (long*)&i;
volatile int k = 0;
int* u = (int*)&k;
k = (int)i;
const int* v = (const int*)&k;
const int * const w = (const int*)&k;
}
/*
gcc constcast.c -o constcast
./constcast
*/
ConstCast.cpp download
int main()
{
const int i = 0;
int* j = (int*)&i; // Deprecated form (C style cast)
j = const_cast<int*>(&i); // Preferred form
// Can't do simultaneous additional casting:
// long* l = const_cast<long*>(&i); // compile error
long* l = (long*)&i; // C style works
volatile int k = 0;
int* u = const_cast<int*>(&k);
u = (int*)&k; // C style works too
// k = const_cast<int>(i); // compile error: not pointer or reference
k = (int)i; // C style works
const int* v = const_cast<const int*>(&k);
v = (const int*)&k; // C style
const int * const w = const_cast<const int*>(&k);
// w = (const int*)&k; // compile error: cannot change constant pointer w
}
/*
g++ ConstCast.cpp -o ConstCast
./ConstCast
*/
Chapter_3 Exercise_3-14 StaticCast | BACK_TO_TOP | ReinterpretCast Exercise_3-15 |
Comments
Post a Comment