When should I introduce a typedef struct or a pointer to a struct?

I am not an expert in the field of non-object-oriented programming languages โ€‹โ€‹of a lower level, and I am in the middle of writing C code for a project at work. I'm trying to create some decent abstract data types for work, and the googling around made me realize that people use structural ADT in two ways. Some people define a data type as a structure:

typedef struct adt { //content here } adt; 

and output it to the world in the header file.

Others define a data type as a pointer to a 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 structure without providing the outside world with any knowledge of what is inside this structure, so programmers can only use the functions presented in the same header file to work with this data type.

Are there any other reasons for choosing another? Is there a general โ€œruleโ€ rule for defining ADTs as structures, and when do we define them as pointers to structures?

+8
c struct typedef abstract-data-type
source share
3 answers

You can send a struct declaration without a typedef - the only differences are:

  • Does the interface look cleaner with or without the struct keyword
  • Does the interface look cleaner with or without an 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 to structures declared forward in the interface header.

If you do not hide the implementation of the structure in the first place, the choice between S1 and S2 is a matter of preference (or sequence). I would not use S3 if it is really an opaque / hidden type.

A personal preference would be to use S1 (explicit struct keyword) for large / complex aggregates and S2 for small structures that you could treat as values, rather than always passing by pointer. YMMV.

+6
source share

The decision to hide or not to hide lies entirely with you as the designer of your library. If you want to reserve the right to change your struct at your discretion in the future, you should not expose any of your members to the โ€œworldโ€. If you provide a struct as a means of communicating with your library in the first place (for example, a struct representing a point in 3D), then you cannot hide your members from the world, as this will defeat the purpose.

+1
source share

read the Linus Torvalds post Chapter 5: Typedefs

+1
source share

All Articles