Consider the following C code snippet:
typedef struct node{
int val;
struct node* left;
struct node* right;
}node;
void inorderTraversal(node *p){
inorderTraversal(p->left);
printf("%d",p->val);
inorderTraversal(p->right);
}
If I write only typedef struct instead of typedef struct node, I get a warning saying “passing argument of incompatible pointer type” when I call inorderTraversal(root) in main(). Why do I get this warning even though the program doesn’t show any error?
If you don’t give a tag name to the struct,
in the struct definition declares a new (incomplete) type
struct node. So when you pass a pointer to that (incomplete) type, where anode*is expected, you’re passing a pointer of an incompatible type.When the struct you define has members that are pointers to the same type, you must be able to name that type in the definition, so the type must be in scope.
If you give the
structa name, the type is – from that point on – in scope and can be referred to, although not yet complete, asstruct node(if the tag isnode). After the typedef is complete, the type can then be referred to as eitherstruct nodeornode, whichever you prefer.But if you don’t give the
structa tag, the type is anonymous until the typedef is complete, and cannot in any way be referred to before that. And since when the lineis encountered, no type that
struct noderefers to is known, that line declares a new type,struct node, of which nothing is known. The compiler has no reason to connect that type with the one currently being defined. So at that point, thestructcontains a member that is a pointer to an unknown incomplete type. Now, ininorderTraversal, when you callwith
node *p, by the definition ofnode,p->leftis a pointer to the unknown incomplete typestruct node. Ifphas been created so thatp->leftis actually a pointer tonode, things will work nevertheless (except possibly on platforms where pointers to different types have different representations), but you’re passing a pointer to one type where a pointer to a different type is expected. Since the one type is incomplete, it is incompatible with the expected type.