Nearby lessons
100 of 124C - Structure Declaration
How to declare a structure in C — the struct keyword and tag, the member list, the mandatory semicolon, typedef for a shorter name, and where in your program the declaration belongs.
The Basic Syntax
Four parts: the struct keyword, a tag, a brace-enclosed member list, and a semicolon:
The Semicolon Is Not Optional
} produces a baffling error. The compiler assumes the next thing is a variable declaration of this new type, so int main() becomes "a struct Student named main" — and the error message points at main, not at the missing punctuation. If a structure definition gives you nonsense errors on the line after it, check the semicolon first.Declaring Members
Members follow the same rules as ordinary variables — and you may combine same-typed ones on one line:
Declaring Variables With the Definition
You can create variables in the same statement as the definition, right after the closing brace:
typedef — Dropping the struct Keyword
struct Student s;, which gets tedious. A typedef gives the type a second, shorter name so you can write Student s; instead.Keep the Tag When You Need Self-Reference
An anonymous typedef has no name to refer to inside its own body. For a linked list you need either the tag or a forward typedef:
A Structure Cannot Contain Itself
A member of the same type would need infinite size. A pointer to the same type is fine — its size is known:
Where to Declare — Scope
A structure declared inside a function is only usable there. Declare at file scope so every function can see the type:
Nested Declarations
One structure can contain another. Declaring the inner type separately keeps it reusable:
Declaring in a Header File
In real projects the definition goes in a .h file so several .c files can share it. Include guards stop double inclusion:
Common Mistakes
- Missing the semicolon after
}— the error appears on the following line. - Omitting the
structkeyword —Student s;without atypedefis an error in C. - A member of the structure's own type — use a pointer instead.
- Self-reference in an anonymous
typedef— keep the tag. - Declaring inside a function — the type is then invisible to other functions.
- Assigning initial values to members in the definition — C has no default member initialisers; initialise the variable instead.
} is there because a structure definition is a declaration statement — the same reason int x; needs one. That is also why you may squeeze variable names in between } and ;.- Syntax: struct Tag { members }; — the closing semicolon is required.
- A definition is a blueprint; it allocates no memory.
- typedef struct { ... } Name; lets you write Name instead of struct Name.
- Declare at file scope so every function can use the type.
- A structure may contain a pointer to its own type, but not itself.