tags:

views:

78

answers:

6

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?

+3  A: 

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.

Pablo Santa Cruz
+2  A: 

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.

sth
A: 

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.

Chuck
If the struct contains a pointer to itself, it needs to have a `struct Frame_s` name. That struct could have a member `struct Frame_s * pointer;`, but not `Frame_t * pointer;`.
David Thornley
A: 

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...

MovieYoda
A: 

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;
DigitalRoss
+1  A: 

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 e.g 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);
Jens Gustedt