Home > OS >  Is it possible to define a var to be a pointer to const when the type is defined as a pointer to a s
Is it possible to define a var to be a pointer to const when the type is defined as a pointer to a s

Time:11-24

Let's say test_t is defined as follows:

typedef struct test_t { 
    void *unused; 
} *(test_t)

Is it possible define a variable to be a pointer to const without modifying the definition of test_t?

const test_t var would be a const pointer to struct test_t, right?

I have this problem since sonarqube recommends to "Make the type of this variable a pointer-to-const" but I can't change the definition since it is used in many other places where the variable should be a pointer to struct test_t.

CodePudding user response:

Do not hide pointers behind typedefs. It is a very bad practice and in your case it makes impossible to declare such variable.

typedef struct test_t { 
    void *unused; 
} test_t;

const test_t *var;

CodePudding user response:

This typedef declaration

typedef struct test_t { 
    void *unused; 
} *(test_t);

declares the name test_t as an alias for the type struct test_t *.

So this declaration

const test_t var;

that may be equivalently written like

test_t const var;

actually denotes the following declaration

struct test_t * const var;

That is it declares the variable var as a constant pointer not as a pointer to a constant object of the type struct test_t.

If you want to declare the variable var as a pointer to constant data then you have to write

const struct test_t *var;

If you want to declare a constant pointer to constant data then you have to write

const struct test_t * const var;

However if you want to declare a constant pointer then you need to initialize it in its declaration.

Otherwise you could rewrite the typedef declaration the following way

typedef struct test_t { 
    void *unused; 
} test_t;

and then write

const test_t *var;

In this case the name test_t is an alias for the type specifier struct test_t and the qualifier const produces the type specifier const struct test_t.

CodePudding user response:

Yes it is possible to do without modifications. You just need to copy-paste the entire typedef and change that, e.g.

typedef const struct test_t { 
    void *unused; 
} *const_test_t;

Of course you couldn't pass this to anything that requires pointer to non-const test_t and such. The fix is (as everyone says here) to not use a typedef to hide pointers wherever they shouldn't be.

  • Related