I have an opaque type in my library defined as:
typedef struct MyOpaqueType* MyType; // easier to type for client code
I can’t pass a pointer-to-const struct around using the typedef, so some functions look like:
void UsePointerToConst ( const struct MyOpaqueType * )
instead of:
void UserPointerToConst( const MyType ) // can't use, is really constant pointer
So, given this, I have two questions:
Is the struct keyword in the parameter list only necessary in C?
Is there a better way to do this? Should I create a typedef such as:
typedef const struct MyOpaqueType* ConstantMyType; ?
Yes.See Jens Gustedt’s answer.Just
typedefthe struct, not the pointer. This is better becausetypedefinstead of one for each of {MyOpaqueType,MyOpaqueType *,MyOpaqueType const *,MyOpaqueType *constandMyOpaqueType const *const} and all variants involvingrestrict(which doesn’t exist in C++),FILE *).There’s also no danger; when someone forgets the
*, they get a compiler error.