Structures and unions

Structures and unions
A structure contains an ordered group of data objects. Unlike the elements of an array, the data objects within a structure can have varied data types. Each data object in a structure is a member or field.

A union is an object similar to a structure except that all of its members start at the same location in memory. A union variable can represent the value of only one of its members at a time.

C++ only beginsIn C++, structures and unions are the same as classes except that their members and inheritance are public by default.C++ only ends

You can declare a structure or union type separately from the definition of variables of that type, as described in Structure and union type definition and Structure and union variable declarations; or you can define a structure or union data type and all variables that have that type in one statement, as described in Structure and union type and variable definitions in a single statement.

Structures and unions are subject to alignment considerations. For information about changing alignment and packing structures, see The _Packed qualifier (C only) and #pragma pack.

Structure and union type definition
A structure or union type definition contains the struct or union keyword followed by an optional identifier (the structure tag) and a brace-enclosed list of members.

Read syntax diagramSkip visual syntax diagram
Structure or union type definition syntax

>>-+-struct-+--------------------------------------------------->
   '-union--'   

                          .-----------------------.         
                          V |         
>--+----------------+--{----member_declaration--;-+--}--;------><
   '-tag_identifier-'                                       

The tag_identifier gives a name to the type. If you do not provide a tag name, you must put all variable definitions that refer to the type within the declaration of the type, as described in Structure and union type and variable definitions in a single statement. Similarly, you cannot use a type qualifier with a structure or union definition; type qualifiers placed in front of the struct or union keyword can only apply to variables that are declared within the type definition.
Posted on by