Structures in C and C++

Declaring a Struct

The syntax for a struct declaration differs between C and C++. Although the C version is still valid in C++, it is slightly clunkier.

In C++:
struct [struct_name]
    type attribute;
    // ...
    [struct_name *struct_attribute;]
} [instance1, [instance2, ...]];

A struct declaration requires the keyword struct, optionally the name of the struct (see below), and a body consisting of one or more attributes. It is possible to optionally include a self-referential pointer, but not possible to include a struct of type struct_name (struct_name struct_attribute).

If one or more structs is immediately desired, the entire declaration can be treated as a type, and the name of one or more instances may follow the declaration. In this case, it is possible to omit struct_name entirely, though this is not advisable.

To declare a struct for use at any other point, the name of the struct, struct_name, can be used as though it were any other type.
struct_name struct_instance [, instance2, ...];
In C:
[typedef] struct [struct_name]
    type attribute;
    type attribute2;
    // ...
    [struct struct_name *struct_instance;]
} [struct_name_t] [struct_instance];
In this case, there are two options: the first is to omit both typedef and struct_name_t, in which case to declare a struct you will need to actually include the struct keyword:
struct struct_name struct_instance;
Or you can use a typedef to declare a struct_name_t type that you can use:
struct_name_t struct_instance;
In either case, if you wish to declare a pointer to a struct inside of the struct, you must use the first syntax, with the keyword struct:
struct struct_name *struct_instance;


Tutorial on structs