[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c

abstract data types, to point or not to point?

dr.oktopus

5/4/2011 4:47:00 PM

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
1 Answer

John Doe

5/5/2011 6:40:00 AM

0

On Wed, 04 May 2011 09:47:13 -0700, dr.oktopus wrote:

> 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
<stdio.h> use "FILE *".

> 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.