Typedef is very useful for portable names, tag names (typedef struct foo Foo;
) and
keeping complicated (function) declarations readable (typedef int
(*cmpfunc)(const void *, const void *);
).
But are there situations in C where a typedef is really truly needed? Where you cannot accomplish the same by simple writing out the derived type.
To clarify a bit: I mean for language users, not implementers. The whole of stdint.h
is a good example of the second category.
Thanks for all your input. I think I can summarise it as:
(u)intN_t
types.va_arg
macro, but I doubt you will encounter these derivative types in practise.Thanks all for your answers. I looked some more myself and found this in C99, J.2 Undefined behaviour:
The behavior is undefined in the following circumstances: [...]
- The type parameter to the
va_arg
macro is not such that a pointer to an object of that type can be obtained simply by postfixing a*
(7.15.1.1).
So when you want to pass/extract complicated derived types to va_arg
such as int (*)[]
you need to typedef
this type to something for which this is possible (updated/corrected):
typedef int (*intarrptr)[4];
intarrptr x = va_arg(ap, intarrptr);
Since it is difficult to find and actual useful case for this one might conclude that it is not a strong argument for the necessity of typedef
.
A typedef
is, by definition, an alias. As such, you always could replace the alias with the actual type. It wouldn't be an alias otherwise.
That doesn't mean avoiding typedef
would be a good idea.
From wikipedia:
typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.1
Based on that definition, no it's never required as you can always just write out the expanded form. However, there may be macro definitions which choose a typedef to use based on platform or something else. So always using the expanded form may not be very portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With