Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding const-ness to opaque handle

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?

like image 245
Toby Avatar asked Oct 30 '22 23:10

Toby


1 Answers

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;
like image 63
this Avatar answered Nov 08 '22 06:11

this