Search code examples
cpointersconstants

Why doesn't this generate a warning or error


I have a function that takes a pointer and I accidently declared it as a const. The function changes the pointer value (intentionally) - the actually pointer not the data that the pointer points to.

I wondered why this does not create a warning....

static void CalcCRC(const uint32_t *pData, uint8_t noWords)
{
    
    // Do some other stuff....

    pData = pData + noWords;

    // Do some other stuff....

}

Solution

  • The declaration

    const uint32_t *pData;
    

    will make *pData const, but not pData itself. In other words, what the pointer is referring to is considered const (when accessed through the pointer), but the pointer itself is not const.

    If you want the pointer itself to be const, then you should write

    uint32_t * const pData;
    

    instead.

    If you want to make the pointer itself and what the pointer is referring to const, then you should use the following declaration:

    const uint32_t * const pData;