justnobody
justnobody

Reputation: 327

What's the benefit of a typedef in C?

typedef struct _VIDEO_STREAM_CONFIG_CAPS
{
  GUID guid;
  ULONG VideoStandard;
  SIZE InputSize;
  SIZE MinCroppingSize;
  SIZE MaxCroppingSize;
  int CropGranularityX;
  int CropGranularityY;
  int CropAlignX;
  int CropAlignY;
  SIZE MinOutputSize;
  SIZE MaxOutputSize;
  int OutputGranularityX;
  int OutputGranularityY;
  int StretchTapsX;
  int StretchTapsY;
  int ShrinkTapsX;
  int ShrinkTapsY;
  LONGLONG MinFrameInterval;
  LONGLONG MaxFrameInterval;
  LONG MinBitsPerSecond;
  LONG MaxBitsPerSecond;
}  VIDEO_STREAM_CONFIG_CAPS;

Why not define structure VIDEO_STREAM_CONFIG_CAPS directly instead of involving _VIDEO_STREAM_CONFIG_CAPS?

Upvotes: 4

Views: 2140

Answers (3)

paxdiablo
paxdiablo

Reputation: 882786

Quite simply (at least for me) because some people like to be able to treat user defined types as "primary" types.

Just like I wouldn't like to have to say:

struct int i;

I prefer:

VIDEO_STREAM_CONFIG_CAPS vscc;

to:

struct VIDEO_STREAM_CONFIG_CAPS vscc;

In fact, I usually get rid of the structure tag altogether, preferring:

typedef struct {
    GUID guid;
    ULONG VideoStandard;
    :
} VIDEO_STREAM_CONFIG_CAPS;

The only time I genarally use the tag is if I have to refer to the type within the type definition itself, such as in linked lists:

typedef struct sNode {
    char paylod[128];
    struct sNode *next;
} tNode;

That's because, at the time of creating the definition, tNode doesn't yet exist but struct sNode does (you can think of it as a simple sequencing thing if that makes it easier - struct sNode gets created on line 1 above, tNode on line 4, which means on line 3 where you create the next pointer, you have to use the structure name).

In the case you cite, the structure tag is superfluous at least in the code shown. Whether some other piece of the code declares a variable with the structure name rather than the typedef name is unclear.

Upvotes: 5

Donotalo
Donotalo

Reputation: 13035

In that case, each time a variable of type VIDEO_STREAM_CONFIG_CAPS is declared, the following syntax would be required:

struct VIDEO_STREAM_CONFIG_CAPS vscc;

With typedef struct it is:

VIDEO_STREAM_CONFIG_CAPS vscc;

Upvotes: 3

JoshD
JoshD

Reputation: 12824

In c, you have to put struct in front of a declaration of a struct type. Without this typedef, you'd have to write struct VIDEO_STREAM_CONFIG_CAPS each time you wanted to use it. With the typedef, you can say just VIDEO_STREAM_CONFIG_CAPS as you would in c++.

struct a {};

struct a A;

OR

typedef struct a {} a;

a A;

Upvotes: 3

Related Questions