4

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....

}
  • 1
    See the [The ``Clockwise/Spiral Rule''](https://c-faq.com/decl/spiral.anderson.html) – ikegami Feb 21 '23 at 13:56
  • 1
    `pData = pData + noWords;` is a perfectly legitimate thing to do on its own. It might not make sense within the context of your code, but the compiler can't (and shouldn't) understand your intentions. – Aykhan Hagverdili Feb 21 '23 at 13:59
  • [always a useful website](https://cdecl.org/) for deciphering these kinds of declarations (it doesn't understand the `uint32_t` type, so you have to use a bit of imagination). – yano Feb 21 '23 at 14:03

3 Answers3

7

The declaration const uint32_t *pData creates a pointer to a const uint32_t, meaning that what the pointer points to is const, not the pointer itself, so modifying the pointer is legal.

If you did something like this:

*pData = 0;

Then you would get an error for modifying a const type.

dbush
  • 205,898
  • 23
  • 218
  • 273
6

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;
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
3

Given static void CalcCRC(const uint32_t *pData, uint8_t noWords)

a pointer and I accidently declared it as a const. The function changes the pointer value ...

It, the pointer, is not const.

The data it points to is const, so changing the the pointer itself is not something to warn about.

 uint32_t *pData;              // Neither const
 const uint32_t *pData;        // Referenced data is const
 uint32_t * const pData;       // Pointer is const
 const uint32_t * const pData; // Referenced data and pointer are const
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256