Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

structures and typedefs in C

This post is about understanding details in two pieces of C code.
Why this is ok:

typedef struct _api_t api_t;

typedef void (*api_set) (api_t * api;
             int a;
  );

typedef int (*api_read) (api_t * api;
  );
  
struct _api_t
{
  api_set set;
  api_read read;
};

and this isn’t

typedef struct _api_t
{
  api_set set;
  api_read read;
} 
api_t;

typedef void (*api_set) (api_t * api;
             int a;
  );

typedef int (*api_read) (api_t * api;
  );

error: unknown type name ‘api_set’, error: unknown type name ‘api_read’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

These records

typedef void (*api_set) (api_t * api;
             int a;
  );

typedef int (*api_read) (api_t * api;
  );

are incorrect. The compiler should issue error messages.

It seems you mean the following code

typedef struct _api_t api_t;

typedef void (*api_set) (api_t * api, int a );

typedef int (*api_read) (api_t * api  );
  
struct _api_t
{
  api_set set;
  api_read read;
};

This code is correct because in this structure definition

struct _api_t
{
  api_set set;
  api_read read;
};

the names api_set and api_read (defined as function pointers in preceding typedefs) are already defined before they are used in the structure definition.

As for the structure definition in the second code snippet then the names api_set and api_read used in the structure definition are not yet defined

typedef struct _api_t
{
  api_set set;
  api_read read;
} 
api_t;

So the compiler will issue error messages that these names are not defined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading