Consider the following function:
void f(int const* p)
{
*const_cast<int*>(id(p)) = 0;
}
Is this legal if you assume that you falways receive a parameter int*as a parameter? I do not ask if this is good to do, I just want a strictly formal answer.
I'm a little worried that if you can do this, it will be harder for the optimizer to work using consts. Consider a more confusing example:
uintptr_t id(uintptr_t p)
{
static unsigned int const ar[5] {0x12345678, 0x87654321, 0x02468ACE, 0xECA86420, 0x88888888};
for (size_t i = 0; i < 5; ++i)
p ^= ar[2*i % 5];
for (size_t i = 0; i < 5; ++i)
p ^= ar[3*i % 5];
return p;
}
void f(int const* p)
{
uintptr_t q = id(reinterpret_cast<uintptr_t>(p));
*reinterpret_cast<int*>(q) = 0;
}
Would it be legal? And if not, will the parameter change to int* pmake it legal?
source
share