Professional Documents
Culture Documents
Chapter Ghsaghsgystytqtyqtw-7
Chapter Ghsaghsgystytqtyqtw-7
STRUCTURES
STRUCTURES
C++ allows you to group a set of variables together into a single item
known as a structure.
A structure is a set of diverse types of data grouped together under a
unique declaration.
C++ gives you the ability to create a relationship between variables
by packaging them together into a structure
A structure bundles together items that logically belong together.
The members of a structure are attributes describing same object.
For example, a payroll system might keep the variables shown in the
following table.
All of the variables
listed in this table
are related
because they can
hold data about the
same employee.
STRUCTURES
Before a structure can be used, it must be declared. Here is the
general format of a structure declaration:
struct tag // Structure declaration begins with the key word struct and a name.
{
// Variable declarations go here.
}; // Notice the required semi-colon.
The tag is the name of the structure. It is used like a data type
name.
The variable declarations that appear inside the braces declare
the members of the structure.
Here is an example of a structure declaration that holds the payroll
data listed in table above:
struct PayRoll
{
int empNumber;
char name[30];
double hours,
payRate,
grossPay;
};
STRUCTURES
The structure declaration in our example creates
a new data type named PayRoll.
Once the data type has been created you can
define variables of this type with simple definition
statements.
For example, the following statement defines a
variable called deptHead:
PayRoll deptHead;
The data type of deptHead is a PayRoll structure.
The structure tag, PayRoll, is placed before the
variable name just as the word int or double would
be to define variables of those types.
STRUCTURES
Structure variables contain other variables known as
members.
Because deptHead is a PayRoll structure, it contains the
five members listed in the Pay-Roll structure declaration.
This is illustrated in the following figure.
STRUCTURES
Just as it’s possible to define multiple int or double
variables, it’s possible to define multiple structure
variables in a program.
The following statement defines three PayRoll variables:
deptHead, foreman, and associate.
PayRoll deptHead, foreman, associate;
The following figure illustrates the existence of these
three variables.
STRUCTURES
Each of these variables is a separate instance of the
PayRoll structure with its own memory allocated to hold
its members.
Each structure variable contains members with the same
name.
Here are some other examples of structure declarations
and variable definitions: