C Language - What does struct tag; mean?

In C, what does the following statement mean?

Code:
struct socket;

This occurs in many header files:

Code:
cd /usr/include/sys
grep '^struct *[a-z]* *;' *.h
 
It is not a structure definition, that would require braces.

It is not a variable or an allocation of memory, that would require a variable name.

I believe that it is a forward declaration, but I have no idea why a forward declaration of a structure would be required. Can you provide an example of why this would be required?
 
It is there as a placeholder so, if one were to define it elsewhere, it would get flagged by the compiler as a warning or error. That name must be used as a struct elsewhere.
 
A linked list implementation in C requires a forward declaration because a node will have the next pointer pointing to an object of type of the node itself. You can't do that without a forward declaration

Code:
struct list_node {
 ....
 struct list_node *next; /* What the heck is struct list_node ???  die here */
};
/* struct list_node isn't known until this point */

Code:
struct list_node;

...

struct list_node {
 ....
 struct list_node *next; /* Everything ok, struct list_node is known */
};
 
Code:
struct list
{
    int x;
    struct list *next;
};

...works perfectly fine, produces no warning, and it's C99 clean. 8.2-RELEASE, base system cc. Besides, none of the schoolbook examples I've seen during my college studies used forward declaration for list implementations.

To answer OP's question, it's a simple forward declaration. You declare the variable, but the body will come on later. Let's say that you want to keep your .h files unbloated and you want to keep one-liners there only, forward declare a struct, and then do a full declaration in some other .c file belonging to same project.
 
Wouldn't the source files be even less bloated without the forward declaration?

Why would the compiler accept struct foo; and not int;

Inquiring minds...
 
Forward declarations like this are used when you want to use the type (in certain contexts), but not provide the definition of it. You can't declare objects of that type, but you can declare pointers and references (in C++) to it.

For example, you can have something like this in a header file, while having the definition of "struct blah" in a C/C++ file:
Code:
struct blah;
void foo (struct blah *p);
 
Back
Top