views:

127

answers:

2

Hi, I don't know why this simple code is not working. Can someone please explain me?

int main()
{
    const char* c = "ret";
    typedef unsigned char GOK_UINT8;
    typedef GOK_UINT8* pGOK_UINT8;
    const pGOK_UINT8  y = reinterpret_cast<const GOK_UINT8*>(c);

    return 0;
}

Can someone tell me why the reinterpret_cast should not work?

Thanks, Gokul.

+10  A: 

Can someone tell me why the reinterpret_cast should not work?

AFAICS, the reinterpret_cast should work fine, but the assignment afterwards should cause an error.

That's because a const GOK_UINT8* is a non-const pointer to const GOK_UINT8 objects, while a const pGOK_UINT8 is a const pointer to non-const objects.
The former protects the object referred to, the latter the pointer referring to the object. If the assignment would be allowed, you could then change the object that the const GOK_UINT8* meant to protect from changing.


Note that typedefed pointers behave strange that way. That's because of the strange declaration syntax of const in (C and thus also in) C++: A const protects the thing to its left, unless there isn't anything, then it protects the thing to its right. So in T const and in T const*, the object of type T is protected, while in T* const the pointer to an object of type T is protected. If you have

typedef T* TPtr;

then TPtr const again makes the pointer const. So does const TPtr. A typedefed pointer either points to const or non-const objects, you can't change that. You can't stuff a const into the vicinity of TPtr and expect that to protect the objects the pointer refers to.

(BTW, this is why STL classes have to define both an iterator and a const_iterator.)

sbi
+1, correct answer. @Gokul: Try this instead of line 6: `const GOK_UINT8* tmp = reinterpret_cast<const GOK_UINT8*>(c); const pGOK_UINT8 y = tmp;`. You will see the reinterpret_cast works fine, it's the type mismatch in the assignment that results in an error. That being said, be aware that your code exhibits about as many bad coding practices as it has lines... I hope this is for experimentation only. ;-)
DevSolar
+2  A: 

Yep sbi is correct.

Modified your code accordingly,

const char* c = "ret";
typedef unsigned char GOK_UINT8;
typedef const GOK_UINT8* pGOK_UINT8;
pGOK_UINT8 y = reinterpret_cast<const GOK_UINT8*>(c);
printf("%s", y);
user001