0

Possible Duplicate:
Purpose of struct, typedef struct, in C++
typedef struct vs struct definitions

I am aware that there are two ways of declaring structs in C

struct point{
    int x, y;
};

and:

typedef struct{
    int x, y;
} point;

but what is the difference between these two methods and when would I use the typedef method and not the other ?

Community
  • 1
  • 1
lilroo
  • 2,928
  • 7
  • 25
  • 34

3 Answers3

2

differences:

  1. The first one is valid C89;
  2. The first one doesn't make the label of the struct ("point") to be a complete type definition, so you can use point p; with the second one only.
  3. Our C programming God, Linus Torvalds strongly encourages not using typedefs for structs (except if there's an explicit need for hiding the actual fields and type behind an opaque struct) as it diminishes readability.
  • Do you have a reference/link for the `strongly encourages not using typedefs for structs` part? . . . And another one for the `Our C programming God, Linus Torvalds`? . . . – paercebal Aug 26 '12 at 10:37
  • @paercebal http://www.kernel.org/doc/Documentation/CodingStyle –  Aug 26 '12 at 14:03
1

There is only one way to declare a struct in C, using the struct keyword, optionally followed by the name of the structure, then followed by the member fields list in braces. So you could have:

  struct point_st {
     int x, y;
  };

Here point_st is the name (or tag) of your structure. Notice that structure names have a different namespace in C than types (this is different in C++). So I have the habit of suffixing structure names with _st as shown above.

You can (independently) define a type name using typedef, e.g.

  typedef struct point_st Point;

(you can use typedef on any C type, BTW).

For exemple Gtk and Glib has a lot of opaque types which are such opaque structures; only the implementation knows and cares about the structure members.

Of course the compiler needs to know the field of a structure to allocate it; but if you only use pointers to an opaque structure, you don't need to declare the structure (i.e. its fields in braces).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

With first form, variable declaration must be:

struct point A;

Second form allows to declare variables without struct like

point B;
Stephane Rouberol
  • 4,286
  • 19
  • 18