Add Const-Ness to the Opaque handle

If I create a C module, it provides the user with a pointer to the forward declaration structure, as shown below:

typedef struct FOO_Obj *FOO_Handle;

If I then declare the function prototype to use it as a const qualified parameter:

void FOO_work(const FOO_Handle fooHandle) ;

How to apply constants?

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

Or UB?

B. (The code you provided has no undefined behavior.)

Function call

void FOO_work(const FOO_Handle fooHandle);

Equivalent to

void FOO_work(struct FOO_Obj* const fooHandle);

The variable fooHandle in the function points the pseudo pointer to the const pointer of the non-const structure FOO_Obj object. You will not be able to add the const qualifier to fooHandle to make it A pointer to a const object.

In contrast, if you want to have a pointer to a const object and keep the structure hidden, you must create another typedef:

< pre>typedef const struct FOO_Obj* FOO_ConstHandle;

If I create a C module, it provides the user with a pointer to the forward declaration structure, as shown below: < p>

typedef struct FOO_Obj *FOO_Handle;

If I then declare the function prototype to use it as a const qualified parameter:

< /p>

void FOO_work(const FOO_Handle fooHandle);

How to apply constants?

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

Or UB?

B. (The code you provided has no undefined behavior.)

Function call

void FOO_work(const FOO_Handle fooHandle);

Equivalent to

void FOO_work(struct FOO_Obj* const fooHandle);< /pre> 

The variable fooHandle in the function points the pseudo pointer to the const pointer of the non-const structure FOO_Obj object. You will not be able to add the const qualifier to fooHandle to make it a pointer to the const object.

In contrast, if you want to have a pointer to a const object and keep the structure hidden, you must create another typedef:

typedef const struct FOO_Obj* FOO_ConstHandle;

Leave a Comment

Your email address will not be published.