Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this generate a warning or error [duplicate]

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

}
like image 549
ElecDesigner Avatar asked Oct 21 '25 04:10

ElecDesigner


2 Answers

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.

like image 83
dbush Avatar answered Oct 22 '25 20:10

dbush


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;
like image 39
Andreas Wenzel Avatar answered Oct 22 '25 19:10

Andreas Wenzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!