Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I typedef struct vs. pointer to struct?

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?

like image 502
Phonon Avatar asked Feb 15 '12 15:02

Phonon


1 Answers

You can forward declare a struct without typedef too - the only distinctions are:

  • whether the interface looks cleaner with or without the keyword struct
  • whether the interface looks cleaner with or without the explicit pointer *

Eg.

struct S1;
typedef struct S2 S2;
typedef struct S3_s *S3;

void foo1(struct S1 *arg);
void foo2(S2 *arg);
void foo3(S3);

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 S1 and S2 is a matter of preference (or consistency). I wouldn't use S3 unless it's a really opaque/hidden type.

Personal preference would be to use S1 (explicit struct keyword) for big/complex aggregates, and S2 for small structs you might treat like values and not always pass by pointer. YMMV.

like image 54
Useless Avatar answered Oct 19 '22 03:10

Useless