Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Necessity of const specifier in cast

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

like image 759
z0lupka Avatar asked Mar 31 '26 22:03

z0lupka


1 Answers

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:

  1. You need no const in cast.
  2. If you use 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.
like image 184
red0ct Avatar answered Apr 02 '26 13:04

red0ct



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!