Like arrays, structures are also used to store a list of data items in a single variable. However, these data items may be of different data types. Structures are used whenever a programmer requires binding the same or different types of related data items together into a single entity.
A structure is defined as a collection of data items of either same or different data type referred to by a common name. The various data items of a structure are known as members (also known as elements or fields) of a structure.
In order to use members of a structure in a program, a structure must be defined first. The definition of a structure informs the C++ compiler about the type and the number of the data members forming the structure. The syntax for defining a structure is
To understand the concept of structure definition, consider this example.
Example: A code segment to demonstrate structure definition
In this example, a structure sales_record is defined with four members, namely, grade, item_code, item_quantity and item_rate. Note that the structure members are of different data types.
While defining a structure in C++, some important points should always be kept in mind.
• A structure member can have the same name as the name of the structure.
• Two members within a structure cannot have the same name. However, two members of different structures can have the same name.
• A structure cannot have the same name as the name of a variable defined outside the structure. However, a structure member can have the same name as the name of a variable defined outside the structure.
• A member of a structure cannot be initialized within the structure definition.