0

I have the following code

struct A { }

typedef struct A *B;

At this point, I want to declare a function which takes a const B. In other words, I want to create a function

void funct(const struct A *val);

However when I do

const B b1 = ...;

my compiler claims it evaluates to

struct A *const b1 = ...;

I want declare a variable of data type B such that it evaluates to either

const struct A *b1;
// or
const struct A *const b1;

How can this be done? Why does the typedef evaluate to something I don't expect?

enter image description here

Hatefiend
  • 3,416
  • 6
  • 33
  • 74
  • I suggest that you just use `typedef` to define a type of something like `typedef struct A objectA;` and then in your code you can do `const objectA *pObject;` or you could do `objectA * const pObject;`. You could also use `typedef` to define a const variation of the pointer type if you wanted to go that route. In general it is much better to not hide a pointer definition within a `typedef` though I do have to admit that I have done it once or twice myself for a special implementation of an opaque data area that I wanted to use as an array. It was special circumstances. – Richard Chambers Jan 09 '19 at 02:15
  • @RichardChambers Unfortunately I need to do the `typdef struct A *B` to [completely protect my struct members](https://stackoverflow.com/a/2672068/4718288). In that link, you can see the strategy I'm using to make de-referencing members of `B` impossible. That will ensure encapsulation. – Hatefiend Jan 09 '19 at 02:33
  • the typedef evaluates to exactly what is expected. You are expecting to be able to insert a const after having created the typedef. Perhaps you need another typedef to describe the const version. – dgsomerton Jan 09 '19 at 02:50
  • @Hatefiend `typedef` is syntactic sugar, a way to label a particular type. In the link you provide the `typedef` is to there to make it less cumbersome, fewer characters to type, for the person using the library. The example forward declares the struct then does a `typedef` using the forward declared struct to define a type of pointer to the struct. However all the places where `SomeThing` is used, it could also be `struct SomeStruct *`. – Richard Chambers Jan 09 '19 at 07:07

0 Answers0