Suppose I have some code like this:
void foo (void *ptr) {
const struct some *azaza = (const struct some *)ptr;
azaza->some_field = 123; // inadvertently assignment => error
// ...
Is the const specifier really needed in cast?
EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).
In your specific case you don't even need a cast. In case of void * cast is needed only when dereferencing. So it is sufficient to do:
const struct some *azaza = ptr;
But for the sake of interest,
#gcc test.c:
// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object
// 2)
struct some *azaza = (const struct some *)ptr; // (!)warning: initialization discards ‘const’ qualifier
azaza->some_field = 123;
#gcc test.c -pedantic-errors:
// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object
// 2)
struct some *azaza = (const struct some *)ptr; // error: initialization
// discards ‘const’ qualifier
azaza->some_field = 123;
To sum up:
const in cast.const only in cast (for some odd reason ._.) and without -pedantic-errors - an accidently assignment will not result in an error what is fraught with consequences.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With