Saturday, April 28, 2012

8.47

Given the following C++ declarations,


double* p = new double(2);
void* q;
int* r;


which of the following assignments does the compiler complain about?


q = p;
p = q;
r = p;
p = r;
r = q;
r = (int*)q;
r = static_cast<int*>(q);


r = static_cast<int*>(p);
r = reinterpret_cast<int*>(p);

Try to explain the behavior of the compiler. Will *r ever have the value 2 after one of the assignments to r? Why?

q is void, and so assigning it p is fine
r = reinterpret_cast<int*>(p) forces the conversion regardless of types


the rest produce errors as follows:

p = q                                       cannot convert from void* to double*
r = p                                        cannot convert from double* to int*
p = r                                        cannot convert from int* to double*
r = q                                        cannot convert from void* to int*
r = (int*)q                                q is being used without being initialized
r = static_cast<int*>(q)         q is being used without being initialized
r = static_cast<int*>(p)         cannot convert from double* to int*


r should have the value of 2 after r = reinterpret_cast<int*>(p)

No comments:

Post a Comment