I’m not an expert on lower-level non-object-oriented programming languages, and I’m in the middle of writing some C code for a project at work. I’m trying to create some decent abstract data types to work with, and Googling around made me realize that people use struct-based ADT’s in two ways. Some people define a data type as a struct:
typedef struct adt {
//content here
} adt;
and expose it to the world in the header file.
Others define a data type as a pointer to struct:
// In .c file:
typedef struct adt_s {
//content here
} adt_s, *adt;
// In .h file:
typedef struct adt_s *adt;
I understand that this approach allows you to typedef a struct without giving the outside world any knowledge of what’s inside this struct, so programmers can only use functions supplied in the same header file to operate on this data type.
Are there an other reasons to pick on over the other? Is there a general “rule of thumb” for when the define ADT’s as structs and when do we define them as pointers to structs?
You can forward declare a struct without typedef too – the only distinctions are:
struct*Eg.
Obviously this only applies for forward-declared structures in an interface header.
If you’re not hiding the structure implementation in the first place, choosing between
S1andS2is a matter of preference (or consistency). I wouldn’t useS3unless it’s a really opaque/hidden type.Personal preference would be to use
S1(explicit struct keyword) for big/complex aggregates, andS2for small structs you might treat like values and not always pass by pointer. YMMV.