typedef struct

M

Martin Vorbrodt

why would you bother writing:

typedef struct S {
} S_t;

instead of just:

struct S {
};

and the just use S, or struct S (in plain C) ?

what is the advantage of declaring struct S and then a typedef for it S_t
???
 
P

Pete Becker

Martin said:
what is the advantage of declaring struct S and then a typedef for it S_t
???

In C you can create objects with just the typedef name:

S_t object;

That's shorter than having to write 'struct' everywhere:

struct S object;

Other than that, they're equivalent.
 
I

Ivan Vecerina

: why would you bother writing:
:
: typedef struct S {
: } S_t;
:
: instead of just:
:
: struct S {
: };
:
: and the just use S, or struct S (in plain C) ?
:
: what is the advantage of declaring struct S and then a typedef for it
S_t
: ???

What I would typically see is more something like:
typedef struct S_t { /*...*/ } S;

This style trick is useful in C code, to allow one to use 'S'
alone as a type identifier (instead of being required to always
prepend the keyword 'struct' to refer to the struct type in C).

The 'S_t' struct identifier is optional above. It can be useful
when one wants to forward-declare 'S':
typedef struct S_t S; // forward declaration of S, would not
// be possible without 'S_t' in the decl.

This typedef trick is totally pointless in C++, except when
a more transparent backwards-compatibility with C is desired.


Ivan
 
V

Victor Bazarov

Martin said:
why would you bother writing:

typedef struct S {
} S_t;

instead of just:

struct S {
};

and the just use S, or struct S (in plain C) ?

what is the advantage of declaring struct S and then a typedef for it S_t
???

The code that uses that struct under the typedef-id (S_t) would be the
same in C++ or C (if you intend to make it source-portable).

V
 
I

Ivan Vecerina

: Martin Vorbrodt wrote:
: > why would you bother writing:
: >
: > typedef struct S {
: > } S_t;
: >
: > instead of just:
: >
: > struct S {
: > };
: >
: > and the just use S, or struct S (in plain C) ?
: >
: > what is the advantage of declaring struct S and then a typedef for it
S_t
: > ???
:
: The code that uses that struct under the typedef-id (S_t) would be the
: same in C++ or C (if you intend to make it source-portable).

Note that in either case, portability can also be achieved
by writing "struct S" for both C and C++. But this style
feels very passé, if not confusing, to a C++ programmer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top