Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of a typedef in C?

Tags:

c

typedef

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?

like image 980
justnobody Avatar asked Dec 21 '22 22:12

justnobody


1 Answers

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.

like image 80
paxdiablo Avatar answered Jan 06 '23 06:01

paxdiablo