5

If I have created a C module that presents a handle to the user with a pointer to a forward declared struct, like so:

typedef struct FOO_Obj *FOO_Handle;

If I then declare function prototypes that use it as a const qualified parameter thusly:

void FOO_work(const FOO_Handle fooHandle);

How is the const-ness applied?

const struct FOO_Obj *FOO_Handle // A
struct FOO_Obj *const FOO_Handle  // B
const struct FOO_Obj *const FOO_Handle  // C

Or is it UB?

Toby
  • 9,696
  • 16
  • 68
  • 132

1 Answers1

2

B. ( There is no undefined behavior with the code you presented. )

The function call

void FOO_work(const FOO_Handle fooHandle);

is equivalent to

void FOO_work(struct FOO_Obj* const fooHandle);

Variable fooHandle in the function will becode a const pointer to a non-const struct FOO_Obj object. You will not be able to add the const qualifier to fooHandle to make it a pointer to a const object.

Instead, if you want to have a pointer to a const object, and keep the struct hidden, you must make another typedef:

typedef const struct FOO_Obj* FOO_ConstHandle;
this
  • 5,229
  • 1
  • 22
  • 51
  • Thanks. A `const` pointer to non-`const` data is what I need, so I was on the right track – Toby Jul 14 '15 at 14:17