MJ_India said:
Style 1:
struct my_struct
{
...
};
typedef my_struct my_struct_t;
Style 2:
typedef struct my_struct
{
...
}my_struct_t;
Style 3:
typedef struct
{
...
}my_struct_t;
Which style should be preferred while coding and why?
Style 1 is incorrect, I believe. I think you meant the last line to
read
typedef struct my_struct my_struct_t;
Style 3 has the disadvantage that the struct can't contain pointers to
its own type, e.g. for a linked list. These have to be declared as
'struct my_struct *', not as 'my_struct_t *'. On the other hand, it has
the advantage that it forces you to use 'my_struct_t' consistently, rather
than possibly using both 'my_struct_t' and 'struct my_struct' in
different parts of the code and causing confusion.
I personally prefer the corrected version of Style 1, because it is
easier to spot the definition of the type my_struct_t when it's on its
own line, rather than tacked onto the definition of struct my_struct as
in Style 2. It's also easier to find the definition by grepping for
'typedef.*my_struct_t'. But of course it is a matter of taste; there
are equally valid arguments the other way.
Actually, if practical, I would tend to avoid the typedef altogether,
and just use 'struct my_struct' throughout. I like to be reminded what
the type actually is.
Note: you phrased this question like a homework or exam question. If
you use my post as part of an answer to any sort of assignment or exam,
please remember to cite it as a source.