Is is legal to modify a nonconst pointer through a const one like this?

Viewed 154

Consider the following function:

void f(int const* p)
{
    *const_cast<int*>(id(p)) = 0;
}

Is this a legal thing to do assuming f always gets an int* as a parameter? I'm not asking if it's a good thing to do, I just want a strictly formal answer.

What worries me a little is that if you can do this, the optimizer has a way harder job utilizing consts. Consider a more convoluted example:

// identity, always returns what it gets
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 this be legal too? And if not, would changing the parameter to int* p make it legal?

1 Answers
Related