简体   繁体   中英

Typedef struct question

Why would I want to do this?

typedef struct Frame_s
{
int x;
int y;
int z;
} Frame_t;

Also if I want to create an object what do I use Frame_s or Frame_t?

You would use Frame_t .

With typedef you are saying that Frame_t and struct Frame_s are the exact same type .

So these are equivalent sentences:

// 1
Frame_t f;

// 2
struct Frame_s f;

I would use:

typedef struct
{
   int x;
   int y;
   int z;
} Frame_t;

And always declare my vars like this:

Frame_t f1, f2, f3;

Confusion usually comes from places where you use that sentence in a C++ piece of code. If you use C++ with that typedef you can use either:

// 1
Frame_t f;

// 2
Frame_s f;

But if you use a plain C compiler, then //2 is invalid.

Either you use struct Frame_s , or you use Frame_t .

Usually you do such a typedef so that you can use the typedefed name, Frame_t , and don't have to write struct whenever you refer to the type.

Aside from Frame_t being shorter than struct Frame_s there is no real difference.

Another aspect of typedef that has not yet been mentioned in the other replies is that it reserves the identifier and thus may avoid confusion. If you do a forward declaration like that

typedef struct Frame Frame;

you would avoid that some code that may use the same name Frame eg a variable or function.

One very bad traditional example that comes in mind for this is "sys/stat.h" in POSIX: it defines a struct stat and a function stat :

int stat(const char *path, struct stat *buf);

To declare a value of the struct, you could use either struct Frame_s foo or Frame_t foo (the latter is more normal, since that's the whole point of typedefing). My guess is that Frame_s is meant to indicate the struct type itself, while Frame_t is the plain type that's normally used for Frame values.

typedef is used as a short form. So when a function which returns a structure of this type, normally you write -

struct Frame_s *function_name()

The code start to get obfuscated. Function definitions become long etc. With this typedef you get -

Frame_t *function_name()

Clean code! Makes a big difference in maintenance...

So these two declarations are equivalent:

struct Frame_s f;
Frame_t f;

In fact, you could now leave Frame_s out of the declaration as it isn't needed.

typedef struct
{
  int x;
  int y;
  int z;
} Frame_t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM