abstract data types, to point or not to point?

D

dr.oktopus

Hello,
a proper way to implement an opaque type in c language is hide
its implementation in .c files, and typedef a pointer to it in .h like
this:

typedef struct list_st *list;

list new_list (void);
...

However, I note that often this way is a little modified to
keep out the pointer from the declaration of the new type
(example from a stdio.h):

typedef struct __iobuf *FILE;

Perhaps since C programmers want explicit pointers.
An opaque struct typedef'ed without a pointer could
cost in terms of efficiency when passing/receiving
to/from functions, so why risk?
Tell me what you think
 
N

Nobody

a proper way to implement an opaque type in c language is hide
its implementation in .c files, and typedef a pointer to it in .h like
this:

typedef struct list_st *list;

list new_list (void);
..

Arguably the "proper" way to do it would be to just declare the struct in
the header file:

struct list_st;

struct list_st *new_list(void);
..

Just because you can use a typedef, it doesn't mean that you should.
Forcing the user to write:

struct list_st *l = new_list();

means that anyone reading the code has a bit more information about what
is actually happening, while still preventing "illegal" access to the
structure's fields.
However, I note that often this way is a little modified to
keep out the pointer from the declaration of the new type
(example from a stdio.h):

typedef struct __iobuf *FILE;

Your example appears to contradict the point you're making.

FWIW, GNU libc uses:

typedef struct _IO_FILE FILE;
Perhaps since C programmers want explicit pointers.

This particular case is dictated by the standard; the functions in
An opaque struct typedef'ed without a pointer could
cost in terms of efficiency when passing/receiving
to/from functions

If the structure is opaque, you cannot pass it by value or otherwise
create objects of that type (as opposed to a pointer to it), as the
compiler doesn't know its size. You'll get an "incomplete type" (or
similar) error if you try to do this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top