I've gone down a rabbit hole of questions about typedef
, tag and struct namespaces, and leading _
being reserved by either the system libraries or the compilers. My question:
What is the best practice for typedef'ing structs?
For example, here are some possibilities:
typedef struct ll_item {...} ll_item;
typedef struct _ll_item {...} ll_item;
typedef struct ll_item {...} ll_item_type;
typedef struct ll_item {...} LLItemType;
Anyone have experience in which is typically used, and most standard? I've seen textbooks use the leading underscore method for the structure name itself (and I would intuitively use that method as well), but could that pollute that namespace if a system struct
uses that name?
This is all rather subjective. An identifier with a leading underscore is definitely bad practice, as may collides with the standard library/compiler internals, see C 7.1.3:
All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
The most common practice is actually not to use a struct tag at all. There are just a few special cases where they are actually needed, such as self-referencing structs and opaque types etc. Based on that I'd subjectively say that either of these are "best":
typedef struct {...} ll_item;
typedef struct ll_item {...} ll_item;
Because both struct ll_item
(struct tag version) and ll_item
(typedef version) refers to the same object type, even though they happen to exist in different namespaces. struct ll_item
and ll_item
are compatible types.
A self-referencing struct would then look like:
typedef struct ll_item
{
...
struct ll_item* next;
} ll_item;
An opaque type forward declaration would look like:
typedef struct ll_item ll_item;
And an opaque type definition (private) will then not use typedef
but refer to the same type:
struct ll_item { ... };
As for naming, that's just according to your coding standard. ll_item_type
would be fine too, and even ll_item_t
if you don't care about POSIX.
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