I have a code snippet like -
typedef struct {
int data;
struct abc *nxt; // Have not defined the structure of name "abc"
} mynode_t;
Here I have not defined a structure of name "abc". Still this code doesn't throw an error and compiles fine. Can anyone help understand how this piece of code is working fine?
Please note: Instead "abc", even if I give some other name like "xyz", it works
The C language allows pointers to structures which haven't been defined.
Without this feature, it wouldn't be possible to create constructs like the following:
When the compiler encounters
struct LinkedListNode *nxt;in the above,struct LinkedListNodehasn't been defined yet since we're in the process of defining it.Note that code that dereferences
nxtor otherwise needs info about the structure will require the structure to be defined.Incomplete structure pointers are also useful for creating opaque types. For example, a library might present the following interface:
To the user of this library,
LibHandleis opaque, meaning it's only useful as a value to pass to the library functions. This allows the library to change the format ofLibDataover time without causing backwards-compatibility issues.