Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typedef ever required in C?

Tags:

c

typedef

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.

Conclusion

Thanks for all your input. I think I can summarise it as:

  • The C99 library needs typedef to implement the various (u)intN_t types.
  • On C89 you really want to use typedefs yourself to create similar portable types.
  • You might need typedef when using the va_arg macro, but I doubt you will encounter these derivative types in practise.
like image 208
schot Avatar asked Sep 30 '10 09:09

schot


3 Answers

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.

like image 84
schot Avatar answered Nov 19 '22 06:11

schot


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.

like image 22
jamesdlin Avatar answered Nov 19 '22 05:11

jamesdlin


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.

like image 5
jay.lee Avatar answered Nov 19 '22 06:11

jay.lee