Struct keyword in function parameter and const-correctness

I have an opaque type in my library that is defined as:

typedef struct MyOpaqueType* MyType; // easier to type for client code 

I cannot pass the structure of a pointer to const using typedef, so some functions look like this:

 void UsePointerToConst ( const struct MyOpaqueType * ) 

instead:

 void UserPointerToConst( const MyType ) // can't use, is really constant pointer 

So, considering 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, for example:

 typedef const struct MyOpaqueType* ConstantMyType; ? 
+4
source share
3 answers

Is the struct keyword in the parameter list only necessary in C?

Yes. See Jens Gustedt's answer.

Is there a better way to do this?

Just a typedef struct, not a pointer. This is better because

  • you need only one typedef instead of one for each of { MyOpaqueType , MyOpaqueType * , MyOpaqueType const * , MyOpaqueType *const and MyOpaqueType const *const } and all options involving restrict (which is not in C ++),
  • itโ€™s clear for the user that the semantics of the pointer apply, i.e. passing the data type around is really a matter of copying copies (no performance issues), users are less likely to forget to clear after use, C ++ users can use smart pointers, and
  • this is general convention C (think FILE * ).

There is also no danger; when someone forgets * , they get a compiler error.

+5
source

In C ++, it is assumed that a typedef with the same name as struct , while there is no other identifier with this name. So, something like a stat function that takes a struct stat* as an argument:

 int stat(const char *path, struct stat *buf); 

allowed even in C ++. (This is an example of the real world.)

So you're always better with advanced ads like

 typedef struct toto toto; 

which reserves the toto token in the identifier and in the structure namespace. Then you can declare your function interface for C and C ++. But don't forget extern "C" if you want to access it also with C.

See also: this answer to SO and structure tags are not identifiers in C ++ .

+3
source

You don't need a typedef at all in C ++. Just use the ad forward:

 struct MyType; 

Then go to MyType const * , MyType * , MyType const & etc., when and when it is needed.

+2
source

All Articles